问:
Does vulkan has the maximum number limits of logic device creation?
I wrote the following code to test the maximum logic device number.

```<code>#include "vulkan/vulkan.hpp"
#include <cassert>
#include <vector>
#include <iostream>

int main() {

    std::vector<vk::Instance> instances;
    std::vector<vk::Device>   devices;

    try {

        for( ; true; ) {

            vk::InstanceCreateInfo instanceInfo {};
            instances.push_back( vk::createInstance( instanceInfo ) );

            auto physicalDevices = instances.back().enumeratePhysicalDevices();
            if( 0 == physicalDevices.size() )
                return 0;

            vk::DeviceQueueCreateInfo deviceQueueCreateInfo {};
            deviceQueueCreateInfo.queueFamilyIndex = 0;
            deviceQueueCreateInfo.queueCount = 1;

            vk::DeviceCreateInfo deviceCreateInfo {};
            deviceCreateInfo.queueCreateInfoCount = 1;
            deviceCreateInfo.pQueueCreateInfos = &deviceQueueCreateInfo;
            auto device = physicalDevices.front().createDevice( deviceCreateInfo );
            if( !device ) {
                throw 0;
            }
            devices.push_back( device );
        }
    }
    catch( std::system_error e ) {
        std::cout << e.what() << std::endl
            << e.code() << std::endl;
    }
    catch( ... ) {
    }

    for( auto device : devices )
        device.destroy();
    for( auto instance : instances )
        instance.destroy();
    printf( "Maximum device is %d\n", devices.size() );
    return static_cast<int>( devices.size() );
}
</code>```

The following is my test results:
Windows 10 64bit  8G  RAM GTX 750Ti:   Maximum device is 42,
Ubuntu            8G  RAM GTX 750Ti:   Maximum device is 63,
Windows 10 64bit  16G RAM GTX 1080:    Maximum device is 42,
Ubuntu            64G RAM Titan X:     Maximum device is 31,

The test results show that the vulkan has the maximum number limits of logic device creation, and the limits may vary according to the operating system. I don't find any document about the limits, is there any way to get this limits ? Another question, if i want run a large number of vulkan applications on a server, how can i overcome this limits ?

答:
The Vulkan spec only says this:

Multiple logical devices can be created from the same physical device. Logical device creation may fail due to lack of device-specific resources (in addition to the other errors). If that occurs, vkCreateDevice will return VK_ERROR_TOO_MANY_OBJECTS.

So the number of devices you can create is limited (obviously, since each one must use some resources, and all resources are finite), but the number is implementation-dependent.

The Vulkan conformance tests require that you are able to create at least five devices.

It's possible that some of the resources being used are per-process rather than system-wide. Have you tried spawning a bunch of processes, each of which creates a single VkDevice?

But failing that: your only option is to use a different implementation with a higher limit, or lobby the hardware vendor to use less resources per device (or whatever) to support a higher limit.

Body:
I wrote the following code to test the maximum logic device number.

#include "vulkan/vulkan.hpp"
#include <cassert>
#include <vector>
#include <iostream>

int main() {

    std::vector<vk::Instance> instances;
    std::vector<vk::Device>   devices;

    try {

        for( ; true; ) {

            vk::InstanceCreateInfo instanceInfo {};
            instances.push_back( vk::createInstance( instanceInfo ) );

            auto physicalDevices = instances.back().enumeratePhysicalDevices();
            if( 0 == physicalDevices.size() )
                return 0;

            vk::DeviceQueueCreateInfo deviceQueueCreateInfo {};
            deviceQueueCreateInfo.queueFamilyIndex = 0;
            deviceQueueCreateInfo.queueCount = 1;

            vk::DeviceCreateInfo deviceCreateInfo {};
            deviceCreateInfo.queueCreateInfoCount = 1;
            deviceCreateInfo.pQueueCreateInfos = &deviceQueueCreateInfo;
            auto device = physicalDevices.front().createDevice( deviceCreateInfo );
            if( !device ) {
                throw 0;
            }
            devices.push_back( device );
        }
    }
    catch( std::system_error e ) {
        std::cout << e.what() << std::endl
            << e.code() << std::endl;
    }
    catch( ... ) {
    }

    for( auto device : devices )
        device.destroy();
    for( auto instance : instances )
        instance.destroy();
    printf( "Maximum device is %d\n", devices.size() );
    return static_cast<int>( devices.size() );
}

The following is my test results:
Windows 10 64bit  8G  RAM GTX 750Ti:   Maximum device is 42,
Ubuntu            8G  RAM GTX 750Ti:   Maximum device is 63,
Windows 10 64bit  16G RAM GTX 1080:    Maximum device is 42,
Ubuntu            64G RAM Titan X:     Maximum device is 31,

The test results show that the vulkan has the maximum number limits of logic device creation, and the limits may vary according to the operating system. I don't find any document about the limits, is there any way to get this limits ? Another question, if i want run a large number of vulkan applications on a server, how can i overcome this limits ?


来源: stackexchange

问:
Background larger than its container
I am trying to achieve this layout but I'm having problems with setting a background, which should be 50% of the screen size. I thought of setting up an image as background, but there are different colors that should be different on each page.

Is it possible to achieve it using only background-color?

This is how I set the HTML, TS & CSS so far:

```<code><div [class]="getBackground(title)">
  <div class="background-header">
    <img [src]="'assets/assess/Custom.png'" alt="">
    {{title}}
  </div>
  <div class="swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide" *ngFor="let theme of pillar.data; let i = index">
        <button rh-btn-theme  full-btn [ngClass]="{'ripple': true}" [issue]="theme" (click)="presentModal($event, theme);"></button>
      </div>
    </div>
  </div>
</div>
</code>```

TS

```<code>getBackground(pillar) {
  switch (pillar) {
    case "People":
      return "background-people";

    case "Land":
      return "background-land";

    case "Crop":
      return "background-crop";

    case "Business":
      return "background-business";

    default:
      return "background-custom";
  }
}
</code>```

CSS

```<code>  .background-header {
    width: 100%;
    height: 80%;
    display: block;
    position: relative;
    img {
      display: inherit;
      background-color: #000;
    }
  }

  .background-people {
    background-color: #335F6E;
  }
  .background-land {
    background-color: #006533;
  }
  .background-crop {
    background-color: #7F4020;
  }
  .background-business {
    background-color: #F8DC0B;
  }
  .background-custom {
    background-color: map-get($colors, primary);
  }
</code>```

答:
Yes you can do it by background gradient:

.content {
  width: 100%;
  height: 300px;
  border: solid 2px #123;
  background: linear-gradient( red, red 50%, white 50%, white);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='content'></div></code>```

Dont forget genarte cross-browser css. See about background gradient here

ContentLicense: CC BY-SA 3.0

Title: Background larger than its container

Body:
I am trying to achieve this layout but I'm having problems with setting a background, which should be 50% of the screen size. I thought of setting up an image as background, but there are different colors that should be different on each page.

Is it possible to achieve it using only background-color?

This is how I set the HTML, TS & CSS so far:

    {{title}}

        <button rh-btn-theme  full-btn [ngClass]="{'ripple': true}" [issue]="theme" (click)="presentModal($event, theme);"></button>

TS

getBackground(pillar) {
  switch (pillar) {
    case "People":
      return "background-people";

    case "Land":
      return "background-land";

    case "Crop":
      return "background-crop";

    case "Business":
      return "background-business";

    default:
      return "background-custom";
  }
}

CSS

  .background-header {
    width: 100%;
    height: 80%;
    display: block;
    position: relative;
    img {
      display: inherit;
      background-color: #000;
    }
  }

  .background-people {
    background-color: #335F6E;
  }
  .background-land {
    background-color: #006533;
  }
  .background-crop {
    background-color: #7F4020;
  }
  .background-business {
    background-color: #F8DC0B;
  }
  .background-custom {
    background-color: map-get($colors, primary);
  }

Body:
Yes you can do it by background gradient:

.content {
  width: 100%;
  height: 300px;
  border: solid 2px #123;
  background: linear-gradient( red, red 50%, white 50%, white);
}

<div class='content'></div>

Dont forget genarte cross-browser css. See about background gradient here


问:
Intellij IDEA - import project into subversion -choose what to import
How to choose which folders and files from the project to import into Subversion? When I do CVS - Import into version control - Import into Subversion, it simply imports the whole chosen folder. What if I don't want to import .idea folder and project-name.iml file for example? Is there a way to choose what to import?

答:
Even with the latest version of Intellij 2017, this is not a straight forward process to add a new project to Subversion.

As explained by 'another-programmer'
we need to first 'Share Directory' which is new project directory, by either using or creating a directory in subversion.
Then you should see the project files/directories turning green which means ready to check-in.
You can choose which files/dirs to check-in to your new project.


问:
O(n) algorithm to find out the element appearing more than n/2 times
I was asked in an interview to give an O(n) algorithm to print an element that appears more than n/2 times in an array, if there is such an element. n is the size of the array.
I don't have any clue on how to do this. Can anyone help?</p>

答:
It's also the median value, which takes O(n) to find using the median-of-medians algorithm. In C++ you can do this in one line:</p>

```<code>std::nth_element(begin, begin + n/2, begin + n)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It's also the median value, which takes O(n) to find using the median-of-medians algorithm. In C++ you can do this in one line:

std::nth_element(begin, begin + n/2, begin + n)


问:
strip remove '_' unexpectedly
```<code>>>> x = 'abc_cde_fgh'
>>> x.strip('abc_cde')
'fgh'
</code>```

_fgh is expected.

How to understard this result?

答:
strip() removes characters, not a substring.  For example:

```<code>x.strip('abcde_')
'fgh'
</code>```

Title: strip remove '_' unexpectedly

Body:
>>> x = 'abc_cde_fgh'
>>> x.strip('abc_cde')
'fgh'

_fgh is expected.

How to understard this result?

Body:
strip() removes characters, not a substring.  For example:

x.strip('abcde_')
'fgh'


问:
Convert strings to emoji in python
I have a collection of twits and i want to check emojis in them, but it looks like the writing procedure for the collection converted all emojis in string for example '' is ':-)' in text and '' is ':D' and so on with all emojis. If we try to check unicode codepoints for them we get ':-)'.encode('utf-8') equals to b':-)' in the same time ''.encode('utf-8') equals to 'b'\xf0\x9f\x98\x8a and equality check fails. Using utf-16 : ':-)'.encode('utf-16') equals to b'\xff\xfe:\x00-\x00)\x00' and ''.encode('utf-16') is b'\xff\xfe=\xd8\n\xde' . So is there any way to convert text representations such as ':-)' back to emoji ''.

答:
Use a dictionary to convert any text emoticon back to emoji e.g. as follows:

```<code>>>> dict_emo = { ':-)'  : b'\xf0\x9f\x98\x8a',
...              ':)'   : b'\xf0\x9f\x98\x8a',
...              '=)'   : b'\xf0\x9f\x98\x8a',  # Smile or happy
...              ':-D'  : b'\xf0\x9f\x98\x83',
...              ':D'   : b'\xf0\x9f\x98\x83',
...              '=D'   : b'\xf0\x9f\x98\x83',  # Big smile
...              '>:-(' : b'\xF0\x9F\x98\xA0',
...              '>:-o' : b'\xF0\x9F\x98\xA0'   # Angry face
...              }
>>> print( dict_emo[':)'].decode('utf-8'))

>>> print( dict_emo['>:-('].decode('utf-8'))

>>> print( dict_emo[':-D'].decode('utf-8'))

>>>
>>>
>>> dict_emot= { ':-)'  : b'\xf0\x9f\x98\x8a'.decode('utf-8'),
...              ':)'   : b'\xf0\x9f\x98\x8a'.decode('utf-8'),
...              '=)'   : b'\xf0\x9f\x98\x8a'.decode('utf-8'),  # Smile or happy
...              ':-D'  : b'\xf0\x9f\x98\x83'.decode('utf-8'),
...              ':D'   : b'\xf0\x9f\x98\x83'.decode('utf-8'),
...              '=D'   : b'\xf0\x9f\x98\x83'.decode('utf-8'),  # Big smile
...              '>:-(' : b'\xF0\x9F\x98\xA0'.decode('utf-8'),
...              '>:-o' : b'\xF0\x9F\x98\xA0'.decode('utf-8')   # Angry face
...              }
>>> print( dict_emot[':)'] )

>>> print( dict_emot['>:-o'] )

>>> print( dict_emot['=D'] )

>>>
</code>```

Unfortunately, there are at least two tasks remaining:

Text Smiley Faces and Their Meaning are neither stable nor definitive, see also Common examples of emoticons (Computer Definition) and List of emoticons - although there are some attempts to create a resource of all the text smileys and emoticons in the world;

Natural Language Processing: What is an algorithmic way to find all smileys in a text? and how-to eliminate (false) embedded text emoticons like :-) smile in :-)) double chin.

Title: Convert strings to emoji in python

Body:
Use a dictionary to convert any text emoticon back to emoji e.g. as follows:

>>> dict_emo = { ':-)'  : b'\xf0\x9f\x98\x8a',
...              ':)'   : b'\xf0\x9f\x98\x8a',
...              '=)'   : b'\xf0\x9f\x98\x8a',  # Smile or happy
...              ':-D'  : b'\xf0\x9f\x98\x83',
...              ':D'   : b'\xf0\x9f\x98\x83',
...              '=D'   : b'\xf0\x9f\x98\x83',  # Big smile
...              '>:-(' : b'\xF0\x9F\x98\xA0',
...              '>:-o' : b'\xF0\x9F\x98\xA0'   # Angry face
...              }
>>> print( dict_emo[':)'].decode('utf-8'))

>>> print( dict_emo['>:-('].decode('utf-8'))

>>> print( dict_emo[':-D'].decode('utf-8'))

>>>
>>>
>>> dict_emot= { ':-)'  : b'\xf0\x9f\x98\x8a'.decode('utf-8'),
...              ':)'   : b'\xf0\x9f\x98\x8a'.decode('utf-8'),
...              '=)'   : b'\xf0\x9f\x98\x8a'.decode('utf-8'),  # Smile or happy
...              ':-D'  : b'\xf0\x9f\x98\x83'.decode('utf-8'),
...              ':D'   : b'\xf0\x9f\x98\x83'.decode('utf-8'),
...              '=D'   : b'\xf0\x9f\x98\x83'.decode('utf-8'),  # Big smile
...              '>:-(' : b'\xF0\x9F\x98\xA0'.decode('utf-8'),
...              '>:-o' : b'\xF0\x9F\x98\xA0'.decode('utf-8')   # Angry face
...              }
>>> print( dict_emot[':)'] )

>>> print( dict_emot['>:-o'] )

>>> print( dict_emot['=D'] )

>>>

Unfortunately, there are at least two tasks remaining:

Text Smiley Faces and Their Meaning are neither stable nor definitive, see also Common examples of emoticons (Computer Definition) and List of emoticons - although there are some attempts to create a resource of all the text smileys and emoticons in the world;

Natural Language Processing: What is an algorithmic way to find all smileys in a text? and how-to eliminate (false) embedded text emoticons like :-) smile in :-)) double chin.


问:
Database and connections
I am interested in knowing how databases handle connections that are not explicitly closed by the entity that initiated the connection.

Say I have a database that can accept only 2 concurrent connections at a time. I have a piece of code that opens a connection and never closes it. This piece of code runs forever, but it uses the connection only once in it's lifetime but the connection object never goes out of scope, so it is not garbage collected. Say I run 2 instances of this code. Does it mean that until the program is terminated or the connection times out (due to inactivity) the database can accept no more connections?

In the above scenario if the connection object is garbage collected, then is the connection terminated automatically or does it depend on the database driver that I am using or the connection is not terminated at all until I close it explicitly?

If I open a connection in piece of code and I do not close the connection explicitly, but the program terminates then how does the database reclaim that connection?

答:
The underlying protocol for database connections is typically TCP/IP based.  The connection can be terminated in one of several ways:

The server closes it gracefully and receives an acknowledgement from the client;

The client closes is gracefully and receives an acknowledgement from the server;

The connection times out.  The client and server both separately are told by their respective operating systems that the connection has been closed;

The connection is forcefully closed by either side.

In the case of (3), TCP connections must be kept alive by sending dummy messages every so often to avoid a timeout.  Your connection may timeout because neither side is doing this (and for a database connection it's not something you typically want to do).

It's entirely possible for a time for one side to think the connection is closed and hte other side to still believe it is open.  Messages may get sent in those cases (and typically discarded).

Each connection ("socket") uses an operating system resource called a file descriptor (in UNIX parlance, your OS may call it something else), which is a handle to an I/O resource and the same thing used for an open file (again, OSs may vary).

The limit on connections on your database will be the lowest of:

The configured limit for the OS;

The maximum file descriptors allowed for that process (minus any being used for I/O activity); and

(possibly) system settings or policies on connection limits.

If the connection isn't TCP based (eg a filesystem socket as is often used with MySQL on UNIX systems) the principles are in fact very simlar.

Anyway, the moral of the story to take from this is that a database connection--regardless of its form--involves an operating system resource of some kind.  Your program hsa directly or indirectly asked for that resource.  If the program dies, the operating system will reclaim it (perhaps not immediately but eventually).  If the connection gets garbage collected then the resource will be released in much the same way as if it had been forcibly closed.

Its that external resource (and not the code your client is using) that holds the connection open and drives any limits.

OwnerDisplayName: Abhi

Title: Database and connections

OwnerDisplayName: cletus

LastEditorDisplayName: cletus


问:
JQuery Not Working in Chrome
This code works properly in Firefox but not in Chrome, If you need more of the code I would be glad to provide it, a button changes a background image:

```<code>$(document).ready(function() {
var bg = 1;
$("#changePic").click(function () {
    if (bg == 1)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge1.jpg");
        bg=2;
    }
    else if (bg == 2)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge2.jpg");
        bg=3;
    }
    else
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge.jpg");
        bg=1;
    }
  });
});
</code>```

I'm not getting any errors in the Chrome Console. Thanks!

答:
you are not closing the url for the background</p>

```<code> $("#outerWrapper").css("background-image","url(images/background-lodge.jpg)");
                                                               was missing ^
</code>```

Title: JQuery Not Working in Chrome

Body:
This code works properly in Firefox but not in Chrome, If you need more of the code I would be glad to provide it, a button changes a background image:

$(document).ready(function() {
var bg = 1;
$("#changePic").click(function () {
    if (bg == 1)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge1.jpg");
        bg=2;
    }
    else if (bg == 2)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge2.jpg");
        bg=3;
    }
    else
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge.jpg");
        bg=1;
    }
  });
});

I'm not getting any errors in the Chrome Console. Thanks!

Body:
you are not closing the url for the background

 $("#outerWrapper").css("background-image","url(images/background-lodge.jpg)");
                                                               was missing ^


问:
SSRS Report to run based on an event
Here is the scenario the user wants...
The ETL is usually completed at 5 AM and a row is inserted in a table upon successful load.
Starting at 5 AM the SSRS report should look for that row to be inserted, say every 30 seconds.
When it sees a row is inserted and the SSRS report should run which in turn sends an email to the users specified in the subscription.

Is there any way to achieve this without SQL -RD?
Please give me a direction as I am new to MSBI.

Regards,
Chakrapani M

答:
Use a SSIS package with 3 tasks:

SQL Task - Single Row Result set - Check if data based on last run date scenario and then update last-run-date

SQL Task - On success of task 1 run "Windows File Share" SSRS report (say export as PDF or Excel format)

EMAIL Task - On success of task 2 Add file as an attachment and send

Deploy and add the package to a SQL Server job, scheduled for 30 seconds.

Alternatively put the delay (schedule) in the package. I.e. use a For Loop Container (with an optional loop end count) and dump the 3 tasks into it with an additional delay task scenario on failure of task 1 and a exit loop early on success of task 3. Remember to set the MaximumErrorCount of the For Loop to 0 and the each individual task in the loop besides the first task FailPackageOnError property to True in order to avoid the intentional error to call the delay if no result from the ETL.

Title: SSRS Report to run based on an event


问:
Azure Web Job with Quartz failing
I've published a console app as a continuously running web job, using Quartz to manage the scheduling.

Quartz works fine when I run the file locally.

When I run the file as a web job, I can see that it runs on schedule, and does what it's supposed to.

However, when I look at the web job logs, I see errors like this:

```<code>[07/06/2017 09:48:59 > dd118a: ERR ] Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Quartz, Version=2.5.0.0, Culture=neutral, PublicKeyToken=f6b8c98a402cc8a4' or one of its dependencies. The system cannot find the file specified.
</code>```

I'm seeing other, similar questions on here, but typically this involves people having assembly mismatch issues on their local machine.

How do I check to see if this error is critical, and how do I fix it?

Suggestions?

答:
I do a test with the following sample code using Quartz.NET library (v2.5.0), it works fine both on local and deployed as WebJobs.

```<code>using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace QuartzTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter { Level = Common.Logging.LogLevel.Info };

                // Grab the Scheduler instance from the Factory
                IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

                // and start it off
                scheduler.Start();

                // define the job and tie it to our HelloJob class
                IJobDetail job = JobBuilder.Create<HelloJob>()
                    .WithIdentity("job1", "group1")
                    .Build();

                // Trigger the job to run now, and then repeat every 10 seconds
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("trigger1", "group1")
                    .StartNow()
                    .WithSimpleSchedule(x => x
                        .WithIntervalInSeconds(10)
                        .RepeatForever())
                    .Build();

                // Tell quartz to schedule the job using our trigger
                scheduler.ScheduleJob(job, trigger);

                // some sleep to show what's happening
                Thread.Sleep(TimeSpan.FromSeconds(60));

                // and last shut down the scheduler when you are ready to close your program
                scheduler.Shutdown();
            }
            catch (SchedulerException se)
            {
                Console.WriteLine(se);
            }

            //Console.WriteLine("Press any key to close the application");
            //Console.ReadKey();

        }

        public class HelloJob : IJob
        {
            public void Execute(IJobExecutionContext context)
            {
                Console.WriteLine("Greetings from HelloJob!");
            }
        }

    }
}
</code>```

packages.config

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Common.Logging" version="3.3.1" targetFramework="net452" />
  <package id="Common.Logging.Core" version="3.3.1" targetFramework="net452" />
  <package id="Microsoft.Web.WebJobs.Publish" version="1.0.12" targetFramework="net452" />
  <package id="Quartz" version="2.5.0" targetFramework="net452" />
</packages>
</code>```

WebJobs logs

Could not load file or assembly 'Quartz, Version=2.5.0.0, Culture=neutral, PublicKeyToken=f6b8c98a402cc8a4' or one of its dependencies. The system cannot find the file specified.

Please use the Kudu Console to access to your site’s folder and make sure Quartz and its dependencies files are there (D:\home\site\wwwroot\app_data\jobs\continuous{jobname}). And you can try to delete and redeploy your job to your Azure web app.

Besides, Azure WebJob itself can be triggered on a schedule, if possible, you can use it.

Title: Azure Web Job with Quartz failing

Body:
I've published a console app as a continuously running web job, using Quartz to manage the scheduling.

Quartz works fine when I run the file locally.

When I run the file as a web job, I can see that it runs on schedule, and does what it's supposed to.

However, when I look at the web job logs, I see errors like this:

[07/06/2017 09:48:59 > dd118a: ERR ] Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Quartz, Version=2.5.0.0, Culture=neutral, PublicKeyToken=f6b8c98a402cc8a4' or one of its dependencies. The system cannot find the file specified.

I'm seeing other, similar questions on here, but typically this involves people having assembly mismatch issues on their local machine.

How do I check to see if this error is critical, and how do I fix it?

Suggestions?

Body:
I do a test with the following sample code using Quartz.NET library (v2.5.0), it works fine both on local and deployed as WebJobs.

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace QuartzTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter { Level = Common.Logging.LogLevel.Info };

                // Grab the Scheduler instance from the Factory
                IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

                // and start it off
                scheduler.Start();

                // define the job and tie it to our HelloJob class
                IJobDetail job = JobBuilder.Create<HelloJob>()
                    .WithIdentity("job1", "group1")
                    .Build();

                // Trigger the job to run now, and then repeat every 10 seconds
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("trigger1", "group1")
                    .StartNow()
                    .WithSimpleSchedule(x => x
                        .WithIntervalInSeconds(10)
                        .RepeatForever())
                    .Build();

                // Tell quartz to schedule the job using our trigger
                scheduler.ScheduleJob(job, trigger);

                // some sleep to show what's happening
                Thread.Sleep(TimeSpan.FromSeconds(60));

                // and last shut down the scheduler when you are ready to close your program
                scheduler.Shutdown();
            }
            catch (SchedulerException se)
            {
                Console.WriteLine(se);
            }

            //Console.WriteLine("Press any key to close the application");
            //Console.ReadKey();

        }

        public class HelloJob : IJob
        {
            public void Execute(IJobExecutionContext context)
            {
                Console.WriteLine("Greetings from HelloJob!");
            }
        }

    }
}

packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Common.Logging" version="3.3.1" targetFramework="net452" />
  <package id="Common.Logging.Core" version="3.3.1" targetFramework="net452" />
  <package id="Microsoft.Web.WebJobs.Publish" version="1.0.12" targetFramework="net452" />
  <package id="Quartz" version="2.5.0" targetFramework="net452" />
</packages>

WebJobs logs

Could not load file or assembly 'Quartz, Version=2.5.0.0, Culture=neutral, PublicKeyToken=f6b8c98a402cc8a4' or one of its dependencies. The system cannot find the file specified.

Please use the Kudu Console to access to your site’s folder and make sure Quartz and its dependencies files are there (D:\home\site\wwwroot\app_data\jobs\continuous{jobname}). And you can try to delete and redeploy your job to your Azure web app.

Besides, Azure WebJob itself can be triggered on a schedule, if possible, you can use it.


问:
Vim - don't delete upon visual paste
Copying a word into a register, selecting a different word with visual mode, and pasting over the second word deletes the original word in the register.

For example, running vey on Word_1, then running vep on Word_2 now puts Word_2 in the "* register. I would like the "* register to maintain the Word_1 value. Any ideas?

I was thinking of mapping paste in visual mode to a custom range function, saving the register before pasting, and then restoring the register after pasting. I just need some help doing that.

答: Try to install vim-operator-user and vim-operator-replace</p>

Title: Vim - don't delete upon visual paste


问:
ASP.NET MVC Populate DropDown thru ViewBag
I am a beginner to ASP.NET MVC technology.
   In my View page, I have a WebGrid that is bind to data that is passed from Controller. I also want to populate a dropdown list with the list of Tables in the database. I retrieve the tables List from a helper method. I am trying to send the List to the ViewBag and want to populate the dropdown; but can't get it. Some syntax error is only coming or the List is not accessible.

My Controller class :

```<code>        [Authorize]
    public ActionResult Index(int page = 1, string sort = "FirstName", string sortdir = "asc", string search = "")
    {
        int pageSize = 10;
        int totalRecord = 0;
        if (page < 1)
            page = 1;
        int skip = (page * pageSize) - pageSize;
        var data = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);

        // Get Tables List
        ViewBag.TableList = DataFiller.GetTableNames();
        ViewBag.TotalRows = totalRecord;

        return View(data);
    }
</code>```

View file :

```<code>@model List<DataStudio.Models.User>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_MemberLayout.cshtml";

<!-- data is used for grid -->
var grid = new WebGrid(canPage: true, rowsPerPage: 10);
grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage: false);
}

<!-- ERROR LINE   -->
@Html.DropDownList("tableName", @ViewBag.TableList, "Select Table")
</code>```

ERROR

```<code>Error   CS1973  'HtmlHelper<List<User>>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.    1_Views_Member_Index.cshtml Index.cshtml    82  Active
</code>```

The User model doesn't contain any List nor any DropDownList. The drop down is a totally separate combo box, that I want to fill with a List items; it just contains the list of table names from the database.

I am not able to get how do I bind or populate the drop down list with the SelectLiteItem items. I googled a lot, but could not get any example with this scenario. I don't wish to add my List with my model. And, I want to populate the Tables list drop down only once.

Can anyone please help me and guide me how do I achieve the goal. Any help is highly appreciated.

Thanks

Tom

UPDATE:
The DataFilter.GetTableNames() method

```<code>       public static List<SelectListItem> GetTableNames()
    {
        List<SelectListItem> tablesList = new List<SelectListItem>();

        string sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
        string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DMSDbConnectionString"].ToString();

        using (SqlConnection con = new SqlConnection(conStr))
        {
            using (SqlCommand com = new SqlCommand(sql, con)) {
                con.Open();
                using(SqlDataReader sdr = com.ExecuteReader() )
                {
                    while (sdr.Read())
                    {
                        tablesList.Add(new SelectListItem
                        {
                            Text = sdr["TABLE_NAME"].ToString(),
                            Value = sdr["TABLE_NAME"].ToString()
                        });
                    }
                }

                /*
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataSet ds = new DataSet();
                da.Fill(ds);

                DataTable dt = ds.Tables[0];

                tablesList = (from DataRow dr in dt.Rows
                              select new TablesInfo()
                              {
                                  TableCatalog = dr["TABLE_CATALOG"].ToString(),
                                  TableName = dr["TABLE_NAME"].ToString(),
                                  TableSchema = dr["TABLE_SCHEMA"].ToString(),
                                  TableType = dr["TABLE_TYPE"].ToString(),
                              }).ToList();

                    */
                con.Close();
            }
        }
        return tablesList;
    }
</code>```

I had created a class also TablesInfo to populate data in it and use strong typed object. But, as couldn't find a way to populate it, so used SelectListItem.
And as it contains only list of tables, so I don't wish it to be populated on every refresh of the page.

答:
You can't use ViewBag dynamic object which contains List<User> directly to a DropDownList HTML helper, you need to cast it into SelectList instead:

```<code>@Html.DropDownList("tableName", (SelectList)ViewBag.TableList, "Select Table")
</code>```

Additionally, DataFiller.GetTableNames() method call should returns SelectList instance:

```<code>class DataFiller
{
    public SelectList GetTableNames()
    {
        // set select list items here
    }
}
</code>```

NB: I strongly prefer using a strongly typed view model instead using ViewBag or ViewData to pass a list to HTML helper like this:

```<code>@Html.DropDownListFor(model => model.tableName, Model.TableList as SelectList, "Select Table")
</code>```

Related issue:

MVC3 DropDownList + ViewBag issue

Body:
I am a beginner to ASP.NET MVC technology.
   In my View page, I have a WebGrid that is bind to data that is passed from Controller. I also want to populate a dropdown list with the list of Tables in the database. I retrieve the tables List from a helper method. I am trying to send the List to the ViewBag and want to populate the dropdown; but can't get it. Some syntax error is only coming or the List is not accessible.

My Controller class :

        [Authorize]
    public ActionResult Index(int page = 1, string sort = "FirstName", string sortdir = "asc", string search = "")
    {
        int pageSize = 10;
        int totalRecord = 0;
        if (page < 1)
            page = 1;
        int skip = (page * pageSize) - pageSize;
        var data = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);

        // Get Tables List
        ViewBag.TableList = DataFiller.GetTableNames();
        ViewBag.TotalRows = totalRecord;

        return View(data);
    }

View file :

@model List<DataStudio.Models.User>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_MemberLayout.cshtml";

var grid = new WebGrid(canPage: true, rowsPerPage: 10);
grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage: false);
}

@Html.DropDownList("tableName", @ViewBag.TableList, "Select Table")

ERROR

Error   CS1973  'HtmlHelper<List<User>>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.    1_Views_Member_Index.cshtml Index.cshtml    82  Active

The User model doesn't contain any List nor any DropDownList. The drop down is a totally separate combo box, that I want to fill with a List items; it just contains the list of table names from the database.

I am not able to get how do I bind or populate the drop down list with the SelectLiteItem items. I googled a lot, but could not get any example with this scenario. I don't wish to add my List with my model. And, I want to populate the Tables list drop down only once.

Can anyone please help me and guide me how do I achieve the goal. Any help is highly appreciated.

Thanks

Tom

UPDATE:
The DataFilter.GetTableNames() method

       public static List<SelectListItem> GetTableNames()
    {
        List<SelectListItem> tablesList = new List<SelectListItem>();

        string sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
        string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DMSDbConnectionString"].ToString();

        using (SqlConnection con = new SqlConnection(conStr))
        {
            using (SqlCommand com = new SqlCommand(sql, con)) {
                con.Open();
                using(SqlDataReader sdr = com.ExecuteReader() )
                {
                    while (sdr.Read())
                    {
                        tablesList.Add(new SelectListItem
                        {
                            Text = sdr["TABLE_NAME"].ToString(),
                            Value = sdr["TABLE_NAME"].ToString()
                        });
                    }
                }

                /*
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataSet ds = new DataSet();
                da.Fill(ds);

                DataTable dt = ds.Tables[0];

                tablesList = (from DataRow dr in dt.Rows
                              select new TablesInfo()
                              {
                                  TableCatalog = dr["TABLE_CATALOG"].ToString(),
                                  TableName = dr["TABLE_NAME"].ToString(),
                                  TableSchema = dr["TABLE_SCHEMA"].ToString(),
                                  TableType = dr["TABLE_TYPE"].ToString(),
                              }).ToList();

                    */
                con.Close();
            }
        }
        return tablesList;
    }

I had created a class also TablesInfo to populate data in it and use strong typed object. But, as couldn't find a way to populate it, so used SelectListItem.
And as it contains only list of tables, so I don't wish it to be populated on every refresh of the page.

Body:
You can't use ViewBag dynamic object which contains List<User> directly to a DropDownList HTML helper, you need to cast it into SelectList instead:

@Html.DropDownList("tableName", (SelectList)ViewBag.TableList, "Select Table")

Additionally, DataFiller.GetTableNames() method call should returns SelectList instance:

class DataFiller
{
    public SelectList GetTableNames()
    {
        // set select list items here
    }
}

NB: I strongly prefer using a strongly typed view model instead using ViewBag or ViewData to pass a list to HTML helper like this:

@Html.DropDownListFor(model => model.tableName, Model.TableList as SelectList, "Select Table")

Related issue:

MVC3 DropDownList + ViewBag issue


问:
Unable to Inject Dependency ngMaterial
I am looking to develop an application that uses both dirPagination and AngularJS material. However, I am unable to inject the ngMaterial dependency into my application. The angularUtils.directives.dirPagination dependency works fine, but as soon as I add ngMaterial, the AngularJS application crashes.

Here is a Plunker with an example (https://plnkr.co/edit/7N7i9TnMc77Nz6xlNhuk?p=preview). In app.js, which is where I instantiate the module, both dependencies are there. If the line reads:

```<code>angular.module('myApp', ['angularUtils.directives.dirPagination', 'ngMaterial']);
</code>```

Then AngularJS crashes and the page reads {{hello}}. However, since in the controller, I have set $scope.hello to "Hello Plunker!", if the line reads:

```<code>angular.module('myApp', ['angularUtils.directives.dirPagination']);
</code>```

Then the page displays "Hello Plunker!".

What am I doing wrong?

Thanks for your help!

答:
This is a working demo, was having version issue and also order of declaring JS file.

<!DOCTYPE html>

    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

{{hello}}

        <md-toolbar class="md-warn">

HTML 5

      </md-toolbar>

```

Title: Unable to Inject Dependency ngMaterial

Body:
I am looking to develop an application that uses both dirPagination and AngularJS material. However, I am unable to inject the ngMaterial dependency into my application. The angularUtils.directives.dirPagination dependency works fine, but as soon as I add ngMaterial, the AngularJS application crashes.

Here is a Plunker with an example (https://plnkr.co/edit/7N7i9TnMc77Nz6xlNhuk?p=preview). In app.js, which is where I instantiate the module, both dependencies are there. If the line reads:

angular.module('myApp', ['angularUtils.directives.dirPagination', 'ngMaterial']);

Then AngularJS crashes and the page reads {{hello}}. However, since in the controller, I have set $scope.hello to "Hello Plunker!", if the line reads:

angular.module('myApp', ['angularUtils.directives.dirPagination']);

Then the page displays "Hello Plunker!".

What am I doing wrong?

Thanks for your help!

Body:
This is a working demo, was having version issue and also order of declaring JS file.

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
       <script data-require="jquery@*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
    <script data-require="bootstrap@3.1.1" data-semver="3.1.1" src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

  </head>

  <body>
    <div data-ng-app="myApp">
      <div data-ng-controller="myCtrl">
        <h1>{{hello}}</h1>
        <md-toolbar class="md-warn">
         <div class="md-toolbar-tools">
            <h2 class="md-flex">HTML 5</h2>
         </div>
      </md-toolbar>
      </div>
    </div>
  <script>
   var app = angular.module('myApp', ['ngMaterial']);
   app.controller('myCtrl', function($scope, $http) {
   $scope.hello = "Hello Plunker!";
   });

   </script>
  </body>

</html>


问:
Can't Create QR With Text Below
I use this codes for making qr code with custom text below. I tried several methods but I always failed. I need to help.

```<code>// Set the content-type
header('Content-Type: image/png');
header("Content-Disposition: filename='sample.png'");
$main = imagecreatetruecolor(150, 180);
$qr = imagecreatefrompng("https://api.qrserver.com/v1/create-qr-code/?size=150x150&format=png&margin=5&data=sample");
// Create the image
$im = imagecreatetruecolor(150, 30);
// Create some colors
$black = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 399, 29, $black);
// Font path
$font = 'arial.ttf';
// Add the text
imagettftext($im, 20, 0, 5, 25, $black, $font, 'sample');
imagecopymerge_alpha($main, $qr, 0, 0, 0, 0, 150, 150, 100);
imagecopymerge_alpha($main, $im, 0, 150, 0, 0, 150, 30, 100);
imagepng($main);
imagedestroy($main);
</code>```

 And I just see blank page.

答:
You've got an error, but you can't view it in browser because you've set the Content-Type: image/png so for debugging just comment out that line or check your server logs.

First thing I'm reminded of is this answer using a relative path to your font. This is enough to throw a warning that if output to screen would garble your image, and not to mention you won't have the font you needed. I would fix this line.

```<code>$font = realpath(__DIR__.'/arial.ttf');
</code>```

For me, the fatal error was:

Call to undefined function imagecopymerge_alpha()

I'm not sure where you got that code, but I found this question so I assumed it might be related.

```<code>function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    // creating a cut resource
    $cut = imagecreatetruecolor($src_w, $src_h);

    // copying relevant section from background to the cut resource
    imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);

    // copying relevant section from watermark to the cut resource
    imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);

    // insert cut resource to destination image
    imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}
</code>```

Then I noticed the color white was labeled as black and set as both the background and text color - so regardless of which color it was, it wouldn't be visible. So I changed these lines. (- means deleted line and + means added line.)

```<code> // Create the image
 $im = imagecreatetruecolor(150, 30);
 // Create some colors
-$black = imagecolorallocate($im, 255, 255, 255);
+$white = imagecolorallocate($im, 255, 255, 255);
+$black = imagecolorallocate($im, 0, 0, 0);
 imagefilledrectangle($im, 0, 0, 399, 29, $black);
 // Font path
 $font = realpath(__DIR__.'/arial.ttf');
 // Add the text
-imagettftext($im, 20, 0, 5, 25, $black, $font, 'sample');
+imagettftext($im, 20, 0, 5, 25, $white, $font, 'sample');
 imagecopymerge_alpha($main, $qr, 0, 0, 0, 0, 150, 150, 100);
 imagecopymerge_alpha($main, $im, 0, 150, 0, 0, 150, 30, 100);
 imagepng($main);
</code>```

And finally, instead of hardcoding the word sample, just for fun I set that to the query string.

```<code>+$text = $_GET['qr'] ?? 'sample';
+
 // Set the content-type
 header('Content-Type: image/png');
 header("Content-Disposition: filename='sample.png'");
 $main = imagecreatetruecolor(150, 180);
-$qr = imagecreatefrompng("https://api.qrserver.com/v1/create-qr-code/?size=150x150&format=png&margin=5&data=sample");
+$qr = imagecreatefrompng("https://api.qrserver.com/v1/create-qr-code/?size=150x150&format=png&margin=5&data=$text");
 // Create the image
 $im = imagecreatetruecolor(150, 30);
 // Create some colors
@@ -14,7 +16,7 @@ imagefilledrectangle($im, 0, 0, 399, 29, $black);
 // Font path
 $font = realpath(__DIR__.'/arial.ttf');
 // Add the text
-imagettftext($im, 20, 0, 5, 25, $white, $font, 'sample');
+imagettftext($im, 20, 0, 5, 25, $white, $font, $text);
</code>```

GET /

GET /?qr=hello

```<code><?php

$text = $_GET['qr'] ?? 'sample';

// Set the content-type
header('Content-Type: image/png');
header("Content-Disposition: filename='sample.png'");
$main = imagecreatetruecolor(150, 180);
$qr = imagecreatefrompng("https://api.qrserver.com/v1/create-qr-code/?size=150x150&format=png&margin=5&data=$text");
// Create the image
$im = imagecreatetruecolor(150, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $black);
// Font path
$font = realpath(__DIR__.'/arial.ttf');
// Add the text
imagettftext($im, 20, 0, 5, 25, $white, $font, $text);
imagecopymerge_alpha($main, $qr, 0, 0, 0, 0, 150, 150, 100);
imagecopymerge_alpha($main, $im, 0, 150, 0, 0, 150, 30, 100);
imagepng($main);
imagedestroy($main);

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    // creating a cut resource
    $cut = imagecreatetruecolor($src_w, $src_h);

    // copying relevant section from background to the cut resource
    imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);

    // copying relevant section from watermark to the cut resource
    imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);

    // insert cut resource to destination image
    imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}
</code>```

Title: Can't Create QR With Text Below

Body:
I use this codes for making qr code with custom text below. I tried several methods but I always failed. I need to help.

// Set the content-type
header('Content-Type: image/png');
header("Content-Disposition: filename='sample.png'");
$main = imagecreatetruecolor(150, 180);
$qr = imagecreatefrompng("https://api.qrserver.com/v1/create-qr-code/?size=150x150&format=png&margin=5&data=sample");
// Create the image
$im = imagecreatetruecolor(150, 30);
// Create some colors
$black = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 399, 29, $black);
// Font path
$font = 'arial.ttf';
// Add the text
imagettftext($im, 20, 0, 5, 25, $black, $font, 'sample');
imagecopymerge_alpha($main, $qr, 0, 0, 0, 0, 150, 150, 100);
imagecopymerge_alpha($main, $im, 0, 150, 0, 0, 150, 30, 100);
imagepng($main);
imagedestroy($main);

 And I just see blank page.

Body:
You've got an error, but you can't view it in browser because you've set the Content-Type: image/png so for debugging just comment out that line or check your server logs.

First thing I'm reminded of is this answer using a relative path to your font. This is enough to throw a warning that if output to screen would garble your image, and not to mention you won't have the font you needed. I would fix this line.

$font = realpath(__DIR__.'/arial.ttf');

For me, the fatal error was:

Call to undefined function imagecopymerge_alpha()

I'm not sure where you got that code, but I found this question so I assumed it might be related.

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    // creating a cut resource
    $cut = imagecreatetruecolor($src_w, $src_h);

    // copying relevant section from background to the cut resource
    imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);

    // copying relevant section from watermark to the cut resource
    imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);

    // insert cut resource to destination image
    imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}

Then I noticed the color white was labeled as black and set as both the background and text color - so regardless of which color it was, it wouldn't be visible. So I changed these lines. (- means deleted line and + means added line.)

 // Create the image
 $im = imagecreatetruecolor(150, 30);
 // Create some colors
-$black = imagecolorallocate($im, 255, 255, 255);
+$white = imagecolorallocate($im, 255, 255, 255);
+$black = imagecolorallocate($im, 0, 0, 0);
 imagefilledrectangle($im, 0, 0, 399, 29, $black);
 // Font path
 $font = realpath(__DIR__.'/arial.ttf');
 // Add the text
-imagettftext($im, 20, 0, 5, 25, $black, $font, 'sample');
+imagettftext($im, 20, 0, 5, 25, $white, $font, 'sample');
 imagecopymerge_alpha($main, $qr, 0, 0, 0, 0, 150, 150, 100);
 imagecopymerge_alpha($main, $im, 0, 150, 0, 0, 150, 30, 100);
 imagepng($main);

And finally, instead of hardcoding the word sample, just for fun I set that to the query string.

+$text = $_GET['qr'] ?? 'sample';
+
 // Set the content-type
 header('Content-Type: image/png');
 header("Content-Disposition: filename='sample.png'");
 $main = imagecreatetruecolor(150, 180);
-$qr = imagecreatefrompng("https://api.qrserver.com/v1/create-qr-code/?size=150x150&format=png&margin=5&data=sample");
+$qr = imagecreatefrompng("https://api.qrserver.com/v1/create-qr-code/?size=150x150&format=png&margin=5&data=$text");
 // Create the image
 $im = imagecreatetruecolor(150, 30);
 // Create some colors
@@ -14,7 +16,7 @@ imagefilledrectangle($im, 0, 0, 399, 29, $black);
 // Font path
 $font = realpath(__DIR__.'/arial.ttf');
 // Add the text
-imagettftext($im, 20, 0, 5, 25, $white, $font, 'sample');
+imagettftext($im, 20, 0, 5, 25, $white, $font, $text);

GET /

GET /?qr=hello

<?php

$text = $_GET['qr'] ?? 'sample';

// Set the content-type
header('Content-Type: image/png');
header("Content-Disposition: filename='sample.png'");
$main = imagecreatetruecolor(150, 180);
$qr = imagecreatefrompng("https://api.qrserver.com/v1/create-qr-code/?size=150x150&format=png&margin=5&data=$text");
// Create the image
$im = imagecreatetruecolor(150, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $black);
// Font path
$font = realpath(__DIR__.'/arial.ttf');
// Add the text
imagettftext($im, 20, 0, 5, 25, $white, $font, $text);
imagecopymerge_alpha($main, $qr, 0, 0, 0, 0, 150, 150, 100);
imagecopymerge_alpha($main, $im, 0, 150, 0, 0, 150, 30, 100);
imagepng($main);
imagedestroy($main);

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    // creating a cut resource
    $cut = imagecreatetruecolor($src_w, $src_h);

    // copying relevant section from background to the cut resource
    imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);

    // copying relevant section from watermark to the cut resource
    imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);

    // insert cut resource to destination image
    imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}


问:
Using custom Font in react native with expo, loading font every time
I am using Expo and the create-react-native app. I enjoy the live/hot reloading feature on my phone, but I'm wondering about custom fonts.

https://docs.expo.io/versions/v17.0.0/guides/using-custom-fonts.html#loading-the-font-in-your-app

The API for Expo only has directions to load them asynchronously. Do I have to do this on every component I want a custom font on? This seems like it would cause some unnecessary calls when I've already loaded it once.

Is there a way to set the font as global or pass it via props once loaded? It seems like they suggest this approach via their last line in that link:

Note: Typically you will want to load your apps primary fonts before
  the app is displayed to avoid text flashing in after the font loads.
  The recommended approach is to move the Font.loadAsync call to your
  top-level component.

...But they give no explanation on HOW to do that, if that's what they are implying.

So my questions are:

1) Does loading the custom font in multiple times (on each component), cause performance issues? (or maybe it's pulled from cache after the first?)

2) After loading it can you pass the font down via properties or set it as a global?

and finally

3) Is this an Expo only issue? Or a create-react-native app only issue? Or just a livereload/hotloading issue?

Also note, I'm working on Windows/Android

答:
1) You should only load the font once. As you point out, Expo recommends putting the Font.loadAsync method in the componentDidMount() method of your top-level component.

The performance issue you're referring to is probably the magic that's happening behind the asynchronous call—but again, this should only happen once.

2) From that point forward, you can use the font in any child component using the "fontFamily" property on <Text>. As their example (which I modified slightly) shows:

First load the font in your top-level component.

```<code>export default class App extends React.Component {
  componentDidMount() {
    Font.loadAsync({
      'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'),
    });
  }

  render() {
    return (
       <HelloWorld />
    )
  }
}
</code>```

Then use it in any  component in the app. (Prior to the font loading, you will see the system font - San Francisco on iOS, Roboto on Android. This is why Expo recommends setting a loading state... to avoid awkward flashing between the system font and your newly loaded custom font.)

```<code>export default class HelloWorld extends React.Component {
  render() {
    <Text style={{ fontFamily: 'open-sans-bold', fontSize: 56 }}>
      Hello, world!
    </Text>
  }
}
</code>```

3) This is an Expo-related "issue" (or solution... depending on how you look at it). For instance, on iOS, adding a custom font involves several steps (adding the font file to your native project, making sure the font shows in your Bundle Resources, adding the font to Info.plist...). Not sure what the process is for Android, but it's something different and probably annoying, too.

Expo has abstracted that away with their Font module, which allows you to do one thing - and get the same result across platforms. Which is pretty cool, in my book.

Body:
1) You should only load the font once. As you point out, Expo recommends putting the Font.loadAsync method in the componentDidMount() method of your top-level component.

The performance issue you're referring to is probably the magic that's happening behind the asynchronous call—but again, this should only happen once.

2) From that point forward, you can use the font in any child component using the "fontFamily" property on <Text>. As their example (which I modified slightly) shows:

First load the font in your top-level component.

export default class App extends React.Component {
  componentDidMount() {
    Font.loadAsync({
      'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'),
    });
  }

  render() {
    return (
       <HelloWorld />
    )
  }
}

Then use it in any  component in the app. (Prior to the font loading, you will see the system font - San Francisco on iOS, Roboto on Android. This is why Expo recommends setting a loading state... to avoid awkward flashing between the system font and your newly loaded custom font.)

export default class HelloWorld extends React.Component {
  render() {
    <Text style={{ fontFamily: 'open-sans-bold', fontSize: 56 }}>
      Hello, world!
    </Text>
  }
}

3) This is an Expo-related "issue" (or solution... depending on how you look at it). For instance, on iOS, adding a custom font involves several steps (adding the font file to your native project, making sure the font shows in your Bundle Resources, adding the font to Info.plist...). Not sure what the process is for Android, but it's something different and probably annoying, too.

Expo has abstracted that away with their Font module, which allows you to do one thing - and get the same result across platforms. Which is pretty cool, in my book.


问:
Turning simple c algorithm into matlab
It's simple, I want to pick the biggest value of a line, make all other elements in a line equal to zero and then the position with the biggest value shall be transformed into 1.

This is the code:

```<code>float A [3][3];
 A [0][0] = 1.1, A [0][1] = 3.2, A [0][2] = 1.3;
 A [1][0] = 2.1, A [1][1] = 2.2, A [1][2] = 2.3;
 A [2][0] = 3.1, A [2][1] = 3.2, A [2][2] = 3.3;
for (int i=0; i<3; i++) {
  float biggest=-1000000;
  int biggest_position=0;
  for (int y=0; y<3; y++)
     if (A [i][y]>biggest) {
        biggest_position = y;
        biggest = A[i][y];
        cout << "biggest position" << biggest_position << endl;
     }
  for (int y=0; y<3; y++)
     A [i][y] = 0;
  A [i][biggest_position] = 1;
}
for (int i=0; i<3; i++)
   for (int j=0; j<3; j++)
     cout << A [i][j] << endl;
</code>```

So what I need to do to rewrite properly this code in matlab language?

答:
this may be what you want

```<code>a=[1,2,3;2,3,4;3,2,1;2,4,1]
[~,ap]= max(a,[],2);
atr=zeros(size(a))';
atr((1:size(a,1))*size(a,2)-size(a,2)+ap')=1;
atr'
</code>```

and the result:

a =

```<code> 1     2     3
 2     3     4
 3     2     1
 2     4     1
</code>```

ans =

```<code> 0     0     1
 0     0     1
 1     0     0
 0     1     0
</code>```

it seems to be a more simple way by using matrix, you can try it

Title: Turning simple c algorithm into matlab

Body:
It's simple, I want to pick the biggest value of a line, make all other elements in a line equal to zero and then the position with the biggest value shall be transformed into 1.

This is the code:

float A [3][3];
 A [0][0] = 1.1, A [0][1] = 3.2, A [0][2] = 1.3;
 A [1][0] = 2.1, A [1][1] = 2.2, A [1][2] = 2.3;
 A [2][0] = 3.1, A [2][1] = 3.2, A [2][2] = 3.3;
for (int i=0; i<3; i++) {
  float biggest=-1000000;
  int biggest_position=0;
  for (int y=0; y<3; y++)
     if (A [i][y]>biggest) {
        biggest_position = y;
        biggest = A[i][y];
        cout << "biggest position" << biggest_position << endl;
     }
  for (int y=0; y<3; y++)
     A [i][y] = 0;
  A [i][biggest_position] = 1;
}
for (int i=0; i<3; i++)
   for (int j=0; j<3; j++)
     cout << A [i][j] << endl;

So what I need to do to rewrite properly this code in matlab language?

Body:
this may be what you want

a=[1,2,3;2,3,4;3,2,1;2,4,1]
[~,ap]= max(a,[],2);
atr=zeros(size(a))';
atr((1:size(a,1))*size(a,2)-size(a,2)+ap')=1;
atr'

and the result:

a =

 1     2     3
 2     3     4
 3     2     1
 2     4     1

ans =

 0     0     1
 0     0     1
 1     0     0
 0     1     0

it seems to be a more simple way by using matrix, you can try it


问:
How to list all calls of a function at runtime?
Is there any way to list (show in VS, write to file) all callers (objects, functions) of a function while the program is running? Possibly using the debugger?

I need to record all calls (including callers) of a function from the launch of the program to its termination.

A simple scan of the source code or the binary does not do the job because the program could operate as a server which receives requests to call the desired function.

If Visual Studio does not provide this feature, are there any other solutions to this problem?

答: If your program is a .NET application, you can use my Runtime Flow tool to view all callers of a function while the program is running.</p>


问:
Develop Node + Express applications with user authentication without having to log into an account each server change?
I am developing a website heavily embedded with user authentication (using passport). I also have nodemon reloading the server after each server change. However it is quite tedious to have to log in as a user each time to test a new change. Is there a way to avoid having to constantly log in as a user to test every single new server change? I can not find any npm modules that fake a persistent user or solve the problem. Thanks!

The Answer - If you are in a similar situation use this code.

Came back with a solution that works, so for anyone who sees this post in the future. This is how you get simple persistent user authentication. With passport. This assumes you have strategies in place already, and as just tring to make the users stay after server restarts.

```<code>var bodyParser = require('body-parser')
var mongoose = require('mongoose');
var session = require('express-session');
var cookieParser = require('cookie-parser');
const MongoStore = require('connect-mongo')(session);

app.use(session({
resave: true,
saveUninitialized: true,
secret: 'add-secret',
store: new MongoStore({
  url: process.env.MONGODB_URI || "mongodb://localhost/add-url",
  autoReconnect: true,
  clear_interval: 3600
  })
}));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
</code>```

答:
Yup - it sounds like that's EXACTLY what you want: a "mock authentication" module (for testing purposes only).

Here are two possibilities; you might also consider writing your own:

passport-stub

passport-mocked

Body:
I am developing a website heavily embedded with user authentication (using passport). I also have nodemon reloading the server after each server change. However it is quite tedious to have to log in as a user each time to test a new change. Is there a way to avoid having to constantly log in as a user to test every single new server change? I can not find any npm modules that fake a persistent user or solve the problem. Thanks!

The Answer - If you are in a similar situation use this code.

Came back with a solution that works, so for anyone who sees this post in the future. This is how you get simple persistent user authentication. With passport. This assumes you have strategies in place already, and as just tring to make the users stay after server restarts.

var bodyParser = require('body-parser')
var mongoose = require('mongoose');
var session = require('express-session');
var cookieParser = require('cookie-parser');
const MongoStore = require('connect-mongo')(session);

app.use(session({
resave: true,
saveUninitialized: true,
secret: 'add-secret',
store: new MongoStore({
  url: process.env.MONGODB_URI || "mongodb://localhost/add-url",
  autoReconnect: true,
  clear_interval: 3600
  })
}));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());


问:
Dropwizard registering two classes/clients
I have two instances of clients with different configs  that I am creating (timeout, threadpool, etc...), and would like to leverage Dropwizard's metric on both of the clients.

```<code>        final JerseyClientBuilder jerseyClientBuilder = new JerseyClientBuilder(environment)
            .using(configuration.getJerseyClientConfiguration());

        final Client config1Client = jerseyClientBuilder.build("config1Client");
        environment.jersey().register(config1Client);

        final Client config2Client = jerseyClientBuilder.build("config2Client");
        environment.jersey().register(config2Client);
</code>```

However, I am getting

```<code>org.glassfish.jersey.internal.Errors: The following warnings have been detected:
HINT: Cannot create new registration for component type class org.glassfish.jersey.client.JerseyClient:
Existing previous registration found for the type.
</code>```

And only one client's metric shows up.

How do I track both clients' metrics or is it not common to have 2 clients in a single dropwizard app?

答:
environment.jersey().register() has a javadoc listing of Adds the given object as a Jersey singleton component meaning that the objects registered become part of the jersey dependency injection framework. Specifically this method is used to add resource classes to the jersey context, but any object with an annotation or type that Jersey looks for can be added this way. Additionally, since they are singletons you can only have one of them per any concrete type (which is why you are getting a "previous registration" error from Jersey).

I imagine that you want to have two Jersey clients to connect to two different external services via REST/HTTP. Since your service needs to talk to these others to do its work, you'll want to have the clients accessible wherever the "work" or business logic is being performed.

For example, this guide creates a resource class that requires a client to an external http service to do currency conversions. I'm not saying this is a great example (just a top google result for dropwizard external client example). In fact, I think this not a good to structure your application. I'd create several internal objects that hide from the resource class how the currency information is fetched, like a business object (BO) or data access object (DAO), etc.

For your case, you might want something like this (think of these as constructor calls). JC = jersey client, R = resource object, BO = business logic object

```<code>JC1()
JC2()
B1(JC1)
B2(JC2)
R1(B1)
R2(B2)
R3(B1, B2)
environment.jersey().register(R1)
environment.jersey().register(R2)
environment.jersey().register(R3)
</code>```

The official Dropwizard docs are somewhat helpful. They at least explain how to create a jersey client; they don't explain how to structure your application.

If you're using the Jersey client builder from dropwizard, each of the clients that you create should be automatically registered to record metrics. Make sure you're using the client builder from the dropwizard-client artifact and package io.dropwizard.client. (Looks like you are because you have the using(config) method.)

Body:
I have two instances of clients with different configs  that I am creating (timeout, threadpool, etc...), and would like to leverage Dropwizard's metric on both of the clients.

        final JerseyClientBuilder jerseyClientBuilder = new JerseyClientBuilder(environment)
            .using(configuration.getJerseyClientConfiguration());

        final Client config1Client = jerseyClientBuilder.build("config1Client");
        environment.jersey().register(config1Client);

        final Client config2Client = jerseyClientBuilder.build("config2Client");
        environment.jersey().register(config2Client);

However, I am getting

org.glassfish.jersey.internal.Errors: The following warnings have been detected:
HINT: Cannot create new registration for component type class org.glassfish.jersey.client.JerseyClient:
Existing previous registration found for the type.

And only one client's metric shows up.

How do I track both clients' metrics or is it not common to have 2 clients in a single dropwizard app?

Body:
environment.jersey().register() has a javadoc listing of Adds the given object as a Jersey singleton component meaning that the objects registered become part of the jersey dependency injection framework. Specifically this method is used to add resource classes to the jersey context, but any object with an annotation or type that Jersey looks for can be added this way. Additionally, since they are singletons you can only have one of them per any concrete type (which is why you are getting a "previous registration" error from Jersey).

I imagine that you want to have two Jersey clients to connect to two different external services via REST/HTTP. Since your service needs to talk to these others to do its work, you'll want to have the clients accessible wherever the "work" or business logic is being performed.

For example, this guide creates a resource class that requires a client to an external http service to do currency conversions. I'm not saying this is a great example (just a top google result for dropwizard external client example). In fact, I think this not a good to structure your application. I'd create several internal objects that hide from the resource class how the currency information is fetched, like a business object (BO) or data access object (DAO), etc.

For your case, you might want something like this (think of these as constructor calls). JC = jersey client, R = resource object, BO = business logic object

JC1()
JC2()
B1(JC1)
B2(JC2)
R1(B1)
R2(B2)
R3(B1, B2)
environment.jersey().register(R1)
environment.jersey().register(R2)
environment.jersey().register(R3)

The official Dropwizard docs are somewhat helpful. They at least explain how to create a jersey client; they don't explain how to structure your application.

If you're using the Jersey client builder from dropwizard, each of the clients that you create should be automatically registered to record metrics. Make sure you're using the client builder from the dropwizard-client artifact and package io.dropwizard.client. (Looks like you are because you have the using(config) method.)


问:
Jquery and Javascript combined. Code not working
I have written the below code to display a selection of images within a
 tag when a certain button is clicked on a page. The Jquery to hide the
 elements on page load works, but the rest of the code does nothing. Can anyone help me figure this out please?

```<code>    $(document).ready(function(){
    //Create Array for images
    var vanImgArr = new Array("<img src='img\yvr\coalharbour.jpg'>", "<img src='img\yvr\lgbridge.jpg'>", "<img src='img/yvr/yaletown.jpg'/>", "<img src='img\yvr\lgbridge2.jpg'>");
    var sgpImgArr = new Array("<img src='img\sgp\elginbridge.jpg'>", "<img src='img\sgp\mbfc.jpg'>", "<img src='img\sgp\sgpdusk.jpg'>", "<img src='img\sgp\sgppano.jpg'>");
    var aniImgArr = new Array("<img src='img\ani\cat1.jpg'>", "<img src='img\ani\cat2.jpg'>", "<img src='img\ani\dog1.jpg'>", "<img src='img\ani\tandd.jpg'>");
    var absImgArr = new Array("<img src='img\abs\abs1.jpg'>", "<img src='img\abs\abs2.jpg'>", "<img src='img\abs\abs3.jpg'>", "<img src='img\abs\abs4.jpg'>");
    var clickedId;
    var idx = 0;
    //to display images
    function displayImgs(arr)
    {

        if(idx <= arr.length)
        {
            ('#pic').hide();
            ('#pic').html(arr[idx]);
            ('#pic').fadeIn('slow');
            if(idx > arr.length)
            {
                idx = 0;
            }
            else
            {
                idx++;
            }
        };  //button click close
    }//displayImgs method close

    //on page load
    $('p').hide();

    //More info Action
    $('#more').hover(function(){
        $('#info, #info2').fadeIn('slow');
    });

    //Button Click Action
    $(':button').click(function(){
        clickedId = this.id;
        alert(clickedId); //testing
        switch(clickedId)
        {
            case 'yvr':
                displayImgs(vanImgArr);
                break;

            case 'sgp':
                displayImgs(sgpImgArr);
                break;

            case 'ani':
                displayImgs(aniImgArr);
                break;

            case 'abs':
                displayImgs(absImgArr);
                break;
        }//switch/case close
    });//button click close
});
</code>```

Here is my HTML code to go with the above

```<code><!DOCTYPE html>
</code>```

```<code><title>Ricky Deacon CSIS3380-001, Assignment 2, Summer 2017</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="script.js"></script>
</code>```

```<code><table class="t1">

    <tr>
        <th width="25%" rowspan="3"><img src="img\rick2.JPG" alt="RD portrait goes here"></th>
        <th width="50%" colspan="2">Rick Deacon</th>
        <th width="25%" rowspan="3"><img src="img\rick1.JPG" alt="RD portrait goes here"></th>
    </tr>
    <tr>
        <td id="subtitle" colspan="2">Photography Showcase</td>
    </tr>
    <tr>
        <td id="desc" colspan="2">Click the corresponding button to display images from your chosen category.</td>
    </tr>
</table>
<br/>
<br/>
<table class="t2">
    <tr>
        <th>
             <input id="van" type="button" name="submit" value="Show Vancouver Images"/>
         </th>
         <th>
             <input id="sgp" type="button" name="submit" value="Show Singapore Images"/>
         </th>
         <th>
             <input id="ani" type="button" name="submit" value="Show Animal Images"/>
         </th>
         <th>
             <input id="abs" type="button" name="submit" value="Show Abstract Images"/>
         </th>
    </tr>
    <tr>
        <th>
             <p id="info"><a href="https://flickr.com/rick-deacon">Rick Deacon's Flickr</a></p>
        </th>
        <th colspan="2">
            <h1 id="more">More Info and Portfolio Links</h1>
        </th>
        <th>
             <p id="info2"><a href="https://rick-deacon.pixels.com/">Prints For Sale</a></p>
        </th>
    </tr>
</table>
<br/>
<br/>
<p id="pic" align="center">Image Goes Here</p>
</code>```

答:
You are selecting button tag while there is no button tag in your html. You should select input tag using $('input[type="button"]')
but this might not be good practice at the time of debugging so you should assign input tag a name and then select them using
$('input[name="elementname"]').
Second .In "this.id" is not proper syntax you should use $(this).attr('id');</p>

Body:
I have written the below code to display a selection of images within a
 tag when a certain button is clicked on a page. The Jquery to hide the
 elements on page load works, but the rest of the code does nothing. Can anyone help me figure this out please?

    $(document).ready(function(){
    //Create Array for images
    var vanImgArr = new Array("", "", "", "");
    var sgpImgArr = new Array("", "", "", "");
    var aniImgArr = new Array("", "", "", "");
    var absImgArr = new Array("", "", "", "");
    var clickedId;
    var idx = 0;
    //to display images
    function displayImgs(arr)
    {

        if(idx <= arr.length)
        {
            ('#pic').hide();
            ('#pic').html(arr[idx]);
            ('#pic').fadeIn('slow');
            if(idx > arr.length)
            {
                idx = 0;
            }
            else
            {
                idx++;
            }
        };  //button click close
    }//displayImgs method close

    //on page load
    $('p').hide();

    //More info Action
    $('#more').hover(function(){
        $('#info, #info2').fadeIn('slow');
    });

    //Button Click Action
    $(':button').click(function(){
        clickedId = this.id;
        alert(clickedId); //testing
        switch(clickedId)
        {
            case 'yvr':
                displayImgs(vanImgArr);
                break;

            case 'sgp':
                displayImgs(sgpImgArr);
                break;

            case 'ani':
                displayImgs(aniImgArr);
                break;

            case 'abs':
                displayImgs(absImgArr);
                break;
        }//switch/case close
    });//button click close
});

Here is my HTML code to go with the above

<!DOCTYPE html>

<title>Ricky Deacon CSIS3380-001, Assignment 2, Summer 2017</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>

        Rick Deacon

        Photography Showcase

        Click the corresponding button to display images from your chosen category.

             <input id="van" type="button" name="submit" value="Show Vancouver Images"/>

             <input id="sgp" type="button" name="submit" value="Show Singapore Images"/>

             <input id="ani" type="button" name="submit" value="Show Animal Images"/>

             <input id="abs" type="button" name="submit" value="Show Abstract Images"/>

Rick Deacon's Flickr

More Info and Portfolio Links

Prints For Sale

Image Goes Here


问:
Programmatically determine if std::string uses Copy-On-Write (COW) mechanism
Following up on the discussion from this question, I was wondering how does one using native C++ determine programmatically whether or not the std::string implementation they are using utilizes Copy-On-Write (COW)

I have the following function:

```<code>#include <iostream>
#include <string>

bool stdstring_supports_cow()
{
   //make sure the string is longer than the size of potential
   //implementation of small-string.
   std::string s1 = "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789";
   std::string s2 = s1;
   std::string s3 = s2;

   bool result1 = (&s1[0]) == (&s2[0]);
   bool result2 = (&s1[0]) == (&s3[0]);

   s2[0] = 'X';

   bool result3 = (&s1[0]) != (&s2[0]);
   bool result4 = (&s1[0]) == (&s3[0]);

   s3[0] = 'X';

   bool result5 = (&s1[0]) != (&s3[0]);

   return result1 && result2 &&
          result3 && result4 &&
          result5;
}

int main()
{
  if (stdstring_supports_cow())
      std::cout << "std::string is COW." << std::endl;
   else
      std::cout << "std::string is NOT COW." << std::endl;
   return 0;
}
</code>```

The problem is I can't seem to find a C++ tool chain where it returns true. Is there a flaw in my assumption about how COW is implemented for std::string?

Update: Based on kotlinski comments, I've changed the use of writeble references to data() in the function, it now seems to return "true" for some implementations.

```<code>bool stdstring_supports_cow()
{
   //make sure the string is longer than the size of potential
   //implementation of small-string.
   std::string s1 = "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789";
   std::string s2 = s1;
   std::string s3 = s2;

   bool result1 = s1.data() == s2.data();
   bool result2 = s1.data() == s3.data();

   s2[0] = 'X';

   bool result3 = s1.data() != s2.data();
   bool result4 = s1.data() == s3.data();

   s3[0] = 'X';

   bool result5 = s1.data() != s3.data();

   return result1 && result2 &&
          result3 && result4 &&
          result5;
}
</code>```

Note: According N2668: "Concurrency Modifications to Basic String", in the upcoming C++0x standard, COW option will be removed from basic_string. thanks to James and Beldaz for bringing that up.

答:
Using &s1[0] to take the adress is not what you want, [0] returns a writable reference and will create a copy.

Use data() instead, it returns a const char*, and your tests may pass.

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

Body:
Following up on the discussion from this question, I was wondering how does one using native C++ determine programmatically whether or not the std::string implementation they are using utilizes Copy-On-Write (COW)

I have the following function:

#include <iostream>
#include <string>

bool stdstring_supports_cow()
{
   //make sure the string is longer than the size of potential
   //implementation of small-string.
   std::string s1 = "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789";
   std::string s2 = s1;
   std::string s3 = s2;

   bool result1 = (&s1[0]) == (&s2[0]);
   bool result2 = (&s1[0]) == (&s3[0]);

   s2[0] = 'X';

   bool result3 = (&s1[0]) != (&s2[0]);
   bool result4 = (&s1[0]) == (&s3[0]);

   s3[0] = 'X';

   bool result5 = (&s1[0]) != (&s3[0]);

   return result1 && result2 &&
          result3 && result4 &&
          result5;
}

int main()
{
  if (stdstring_supports_cow())
      std::cout << "std::string is COW." << std::endl;
   else
      std::cout << "std::string is NOT COW." << std::endl;
   return 0;
}

The problem is I can't seem to find a C++ tool chain where it returns true. Is there a flaw in my assumption about how COW is implemented for std::string?

Update: Based on kotlinski comments, I've changed the use of writeble references to data() in the function, it now seems to return "true" for some implementations.

bool stdstring_supports_cow()
{
   //make sure the string is longer than the size of potential
   //implementation of small-string.
   std::string s1 = "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789"
                    "012345678901234567890123456789";
   std::string s2 = s1;
   std::string s3 = s2;

   bool result1 = s1.data() == s2.data();
   bool result2 = s1.data() == s3.data();

   s2[0] = 'X';

   bool result3 = s1.data() != s2.data();
   bool result4 = s1.data() == s3.data();

   s3[0] = 'X';

   bool result5 = s1.data() != s3.data();

   return result1 && result2 &&
          result3 && result4 &&
          result5;
}

Note: According N2668: "Concurrency Modifications to Basic String", in the upcoming C++0x standard, COW option will be removed from basic_string. thanks to James and Beldaz for bringing that up.


问:
Get 1 result in first column of the table and get all the results in the second column of the table
I have tables like these:

users

```<code>   id   |   firstname   |   lastname   |   date
--------------------------------------------------
   1    |   paul        |   sy         |   date

   2    |   james       |   curry      |   date

   3    |   kevin       |   leonard    |   date
</code>```

docs_list

```<code>   id   |   user_id   |   url   |   title   |   date
-------------------------------------------------------
   1    |      1      |   url   |   title   |   date
   2    |      2      |   url   |   title   |   date
   3    |      1      |   url   |   title   |   date
</code>```

I want to get 1 result of firstname and lastname and all of the results of  url and title based on where the users.id and docs_list.user_id is equal to the id given ORDER BY docs_list.date DESC.

So this is how I query it:

```<code>SELECT users.first, users.last, docs_list.urlcode, docs_list.title

FROM users

INNER JOIN docs_list

ON users.id = docs_list.user_id

WHERE docs_list.user_id = {$value}

ORDER BY docs_list.date DESC
</code>```

Problem is that, I got so many firstname and lastname results (equal to how many rows I have in the docs_list result). I only need 1 firstname and lastname.

So how can I do it?

答:
Try this query, that i made based on your given table.

```<code>SELECT u.firstname, u.lastname

FROM users u

JOIN docs_list dl

ON u.id = dl.user_id

WHERE dl.user_id = {$value}

GROUP BY 1
</code>```

If you want to get one result one row for firstname and lastname you just can select firstname and lastname only. Because if there's url and title, they have different value for each row so if you group by them i would be error because url and title have different value.
*Correct me if i'm wrong :D

Body:
I have tables like these:

users

   id   |   firstname   |   lastname   |   date
--------------------------------------------------
   1    |   paul        |   sy         |   date

   2    |   james       |   curry      |   date

   3    |   kevin       |   leonard    |   date

docs_list

   id   |   user_id   |   url   |   title   |   date
-------------------------------------------------------
   1    |      1      |   url   |   title   |   date
   2    |      2      |   url   |   title   |   date
   3    |      1      |   url   |   title   |   date

I want to get 1 result of firstname and lastname and all of the results of  url and title based on where the users.id and docs_list.user_id is equal to the id given ORDER BY docs_list.date DESC.

So this is how I query it:

SELECT users.first, users.last, docs_list.urlcode, docs_list.title

FROM users

INNER JOIN docs_list

ON users.id = docs_list.user_id

WHERE docs_list.user_id = {$value}

ORDER BY docs_list.date DESC

Problem is that, I got so many firstname and lastname results (equal to how many rows I have in the docs_list result). I only need 1 firstname and lastname.

So how can I do it?

Body:
Try this query, that i made based on your given table.

SELECT u.firstname, u.lastname

FROM users u

JOIN docs_list dl

ON u.id = dl.user_id

WHERE dl.user_id = {$value}

GROUP BY 1

If you want to get one result one row for firstname and lastname you just can select firstname and lastname only. Because if there's url and title, they have different value for each row so if you group by them i would be error because url and title have different value.
*Correct me if i'm wrong :D


问:
Alteryx - How to Process Sharepoint input which has Drop down list values
I would like to read Sharepoint data which contains attributes for a dropdown list.  I am connecting to Sharepoint using the Alteryx's Sharepoint list connector tool. Alteryx is only returning the data that is already selected from the dropdown. It is not listing the other data available to the dropdown list.

For example, below is my sample input file which has one attribute called Title1 and value is a dropdown list. (Using an Excel sample, since I cant provide the screenshot of Sharepoint since it has confidential data)

In the above image, under Title1, there is a dropdown list that has 6 values and data1 has been selected.

Desired output:

However, Ateryx is reading only the value that is already selected from the dropdown.
It's showing only data1 as an output:

Actual output:

答: One thing to note is that the Alteryx connector returns the list of files listed in the SharePoint. The actual files may be located at a different (physical) shared/network directory. You will need another permission to access the directory to read the actual files. Check with the SharePoint Admin to get the right file directory.</p>

ContentLicense: CC BY-SA 4.0


问:
VS 2015 compiling cocos2d-x 3.3 error "fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration"
When I compile cocos2d-x (version 3.3) using visual studio 2015, an error occured, saying:

fatal error C1189: #error:  Macro definition of snprintf conflicts with Standard Library function declaration (编译源文件 ..\base\s3tc.cpp)

The source code is:

```<code>#ifdef snprintf
    #error Macro definition of snprintf conflicts with Standard Library
             function declaration
#endif
</code>```

Anybody can tell me what's wrong?

答:
Just find the definition of snprintf in your code and undefine it while on VS2015.

Something like:

```<code>#if _MSC_VER < 1900 //vs2015 already have this function
#define snprintf _snprintf_s
#endif
</code>```

Body:
When I compile cocos2d-x (version 3.3) using visual studio 2015, an error occured, saying:

fatal error C1189: #error:  Macro definition of snprintf conflicts with Standard Library function declaration (编译源文件 ..\base\s3tc.cpp)

The source code is:

#ifdef snprintf
    #error Macro definition of snprintf conflicts with Standard Library
             function declaration
#endif

Anybody can tell me what's wrong?

Body:
Just find the definition of snprintf in your code and undefine it while on VS2015.

Something like:

#if _MSC_VER < 1900 //vs2015 already have this function
#define snprintf _snprintf_s
#endif


问:
Why does my BlueJ jar file load some images, but not others?
I used some of the information around this site to find out to use URLs to get images into a jar file; which I want to be able to be used alone. But when I make the jar file with BlueJ, only some images show up.

Its a blackjack game, and only the table canvas shows up, while no cards ever do. Here's the code:

THIS WORKS (the table):

```<code>public class TableComponent extends JLabel{

  BufferedImage table;

  public TableComponent(){
    URL finalTable = getClass().getResource("blackjackTableCanvas.jpg");
        try {
        table = ImageIO.read(finalTable);
    } catch (IOException e) {
        e.printStackTrace();
    }

  }

  @Override
protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    g2.drawImage(table, 0, 0, null);
}...}
</code>```

but this does not (the cards):

```<code>public class CardRender2 extends JComponent{

  BufferedImage image;
  String val;
  String suit;
  String filename;

  public CardRender2(Card card) {
    this.val = card.value.face;
    this.suit = card.suit.toString();
    filename = this.fetchCardFileLabel();

    URL cardview = getClass().getResource("\\card deck\\" + filename + ".png");
    try {

      image = ImageIO.read(cardview);
    } catch (IOException e) {
      e.printStackTrace();
    }

  }
  public CardRender2(){
    this.val = null;
    this.suit = null;
    filename = "DEALER_FIRST_CARD";

    URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
    try {

      image = ImageIO.read(cardview);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    g2.drawImage(image, 0, 0, null);

  }...}
</code>```

my cards are in a folder in the directory I try to import into BlueJ, whereas the table is in the directory root. There are 53 cards in there (incl dealer hidden card) and I'd rather not put all of then in the root. I tried to implement them similarly. How can I do this?

答:
looks like changing from

```<code>URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
</code>```

to

```<code> URL cardview = getClass().getResource("card deck/DEALER_FIRST_CARD.png");
</code>```

did the trick.

Body:
I used some of the information around this site to find out to use URLs to get images into a jar file; which I want to be able to be used alone. But when I make the jar file with BlueJ, only some images show up.

Its a blackjack game, and only the table canvas shows up, while no cards ever do. Here's the code:

THIS WORKS (the table):

public class TableComponent extends JLabel{

  BufferedImage table;

  public TableComponent(){
    URL finalTable = getClass().getResource("blackjackTableCanvas.jpg");
        try {
        table = ImageIO.read(finalTable);
    } catch (IOException e) {
        e.printStackTrace();
    }

  }

  @Override
protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    g2.drawImage(table, 0, 0, null);
}...}

but this does not (the cards):

public class CardRender2 extends JComponent{

  BufferedImage image;
  String val;
  String suit;
  String filename;

  public CardRender2(Card card) {
    this.val = card.value.face;
    this.suit = card.suit.toString();
    filename = this.fetchCardFileLabel();

    URL cardview = getClass().getResource("\\card deck\\" + filename + ".png");
    try {

      image = ImageIO.read(cardview);
    } catch (IOException e) {
      e.printStackTrace();
    }

  }
  public CardRender2(){
    this.val = null;
    this.suit = null;
    filename = "DEALER_FIRST_CARD";

    URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
    try {

      image = ImageIO.read(cardview);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    g2.drawImage(image, 0, 0, null);

  }...}

my cards are in a folder in the directory I try to import into BlueJ, whereas the table is in the directory root. There are 53 cards in there (incl dealer hidden card) and I'd rather not put all of then in the root. I tried to implement them similarly. How can I do this?

Body:
looks like changing from

URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");

to

 URL cardview = getClass().getResource("card deck/DEALER_FIRST_CARD.png");

did the trick.