问:
cast problem from class to interface
```<code>Assembly assembly = Assembly.LoadFrom("Logic\\bin\\Debug\\Logic.dll");
            Type queryManagerType = assembly.GetType("Logic." + HttpContext.Current.Session["lang_name"] + "SearchQueryManager");
            var queryManager = (ISearchQueryManager)Activator.CreateInstance(queryManagerType);

public interface ISearchQueryManager
    {
        IList<Advertisements> ApplyQueries(string searchQuery, int page, int pageSize, string orderBy, out int count);
    }

public class SlovenianSearchQueryManager : ISearchQueryManager
    {
...
}
</code>```

but i get

Unable to cast object of type 'Logic.SlovenianSearchQueryManager' to type 'Logic.ISearchQueryManager'.

EDIT: whole stacktrace

System.InvalidCastException was
  unhandled by user code

  Message="Unable to cast object of type
  'Logic.SlovenianSearchQueryManager' to
  type 'Logic.ISearchQueryManager'."

  Source="ViaMura.Web.Module"

  StackTrace:
         at ViaMura.Web.Module.WebController.GetAdvertismentsByRawQuery(String
  rawQuery, Int32 page, Int32 pageSize,
  String orderBy, Int32& count) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\WebController.cs:line
  32
         at ViaMura.Web.Module.Views.SearchResultsPresenter.OnResultsLoad(Int32
  page, Int32 pageSize, String orderBy)
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\Views\SearchResultsPresenter.cs:line
  43
         at ViaMura.Web.SearchResults.SearchAdvertisments()
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  155
         at ViaMura.Web.SearchResults.Page_Load(Object
  sender, EventArgs e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  149
         at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr
  fp, Object o, Object t, EventArgs e)
         at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
  sender, EventArgs e)
         at System.Web.UI.Control.OnLoad(EventArgs
  e)
         at ViaMura.Web.App_Code.PageControllers.BasePage.OnLoad(EventArgs
  e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\App_Code\PageControllers\BasePage.cs:line 89
         at System.Web.UI.Control.LoadRecursive()
         at System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean
  includeStagesAfterAsyncPoint)

  InnerException:

EDIT2:

```<code>string a1 = typeof (ISearchQueryManager).Assembly.Location;
string a2 = typeof(SlovenianSearchQueryManager).Assembly.Location
</code>```

give me the same result:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary
  ASP.NET
  Files\root\5438a399\53975f83\assembly\dl3\0f9540b5\15407fe2_5db7cb01\Logic.DLL

but

```<code>string a3 = queryManagerType.Assembly.Location;
</code>```

gives me different path:

D:\PROJEKTI\crawler\WebCrawlerSuite\WebCrawler.Logic\bin\Debug\WebCrawler.Logic.dll

答:
In my experience, type mismatch problems like this are always caused by loading types from two different locations, even if you think they should be getting loaded from the same place.

Compare: Two Types not equal that should be

Try looking at the Assembly.Location property of each type in the debugger:

```<code>typeof(ISearchQueryManager).Assembly.Location
typeof(SlovenianSearchQueryManager).Assembly.Location
</code>```

Title: cast problem from class to interface

Body:
Assembly assembly = Assembly.LoadFrom("Logic\\bin\\Debug\\Logic.dll");
            Type queryManagerType = assembly.GetType("Logic." + HttpContext.Current.Session["lang_name"] + "SearchQueryManager");
            var queryManager = (ISearchQueryManager)Activator.CreateInstance(queryManagerType);

public interface ISearchQueryManager
    {
        IList<Advertisements> ApplyQueries(string searchQuery, int page, int pageSize, string orderBy, out int count);
    }

public class SlovenianSearchQueryManager : ISearchQueryManager
    {
...
}

but i get

Unable to cast object of type 'Logic.SlovenianSearchQueryManager' to type 'Logic.ISearchQueryManager'.

EDIT: whole stacktrace

System.InvalidCastException was
  unhandled by user code

  Message="Unable to cast object of type
  'Logic.SlovenianSearchQueryManager' to
  type 'Logic.ISearchQueryManager'."

  Source="ViaMura.Web.Module"

  StackTrace:
         at ViaMura.Web.Module.WebController.GetAdvertismentsByRawQuery(String
  rawQuery, Int32 page, Int32 pageSize,
  String orderBy, Int32& count) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\WebController.cs:line
  32
         at ViaMura.Web.Module.Views.SearchResultsPresenter.OnResultsLoad(Int32
  page, Int32 pageSize, String orderBy)
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\Views\SearchResultsPresenter.cs:line
  43
         at ViaMura.Web.SearchResults.SearchAdvertisments()
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  155
         at ViaMura.Web.SearchResults.Page_Load(Object
  sender, EventArgs e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  149
         at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr
  fp, Object o, Object t, EventArgs e)
         at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
  sender, EventArgs e)
         at System.Web.UI.Control.OnLoad(EventArgs
  e)
         at ViaMura.Web.App_Code.PageControllers.BasePage.OnLoad(EventArgs
  e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\App_Code\PageControllers\BasePage.cs:line 89
         at System.Web.UI.Control.LoadRecursive()
         at System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean
  includeStagesAfterAsyncPoint)

  InnerException:

EDIT2:

string a1 = typeof (ISearchQueryManager).Assembly.Location;
string a2 = typeof(SlovenianSearchQueryManager).Assembly.Location

give me the same result:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary
  ASP.NET
  Files\root\5438a399\53975f83\assembly\dl3\0f9540b5\15407fe2_5db7cb01\Logic.DLL

but

string a3 = queryManagerType.Assembly.Location;

gives me different path:

D:\PROJEKTI\crawler\WebCrawlerSuite\WebCrawler.Logic\bin\Debug\WebCrawler.Logic.dll

Body:
In my experience, type mismatch problems like this are always caused by loading types from two different locations, even if you think they should be getting loaded from the same place.

Compare: Two Types not equal that should be

Try looking at the Assembly.Location property of each type in the debugger:

typeof(ISearchQueryManager).Assembly.Location
typeof(SlovenianSearchQueryManager).Assembly.Location


来源: stackexchange

问:
How to use X Windows with Emacs on Windows 10 Bash?
I am using the Bash on Ubuntu on Windows program to use Emacs for C++.
Right now, I can code everything using the keyboard shortcuts, however, I want to select text with my mouse or set the mark with my mouse instead of always having to use my keyboard.

To get the X Windows System, I already did sudo apt-get install xserver -xorg but emacs still runs in a terminal editor.

I don't know what other commands to use or how to get X Windows to start running.

答:
The default emacs will work with Xming and other options.  The issue is that the default alternative points to the emacs24-nox command.  You need to install 'emacs24' instead, which removes emacs24-nox.

```<code>$ sudo update-alternatives --query emacs
Name: emacs
Link: /usr/bin/emacs
....
Status: auto
Best: /usr/bin/emacs24-nox
Value: /usr/bin/emacs24-nox

$ sudo apt install emacs24

$ sudo update-alternatives --query emacs
Name: emacs
Link: /usr/bin/emacs
...
Status: auto
Best: /usr/bin/emacs24-x
Value: /usr/bin/emacs24-x
</code>```

Make sure that $DISPLAY is set correctly.

```<code>export DISPLAY=localhost:0.0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The default emacs will work with Xming and other options.  The issue is that the default alternative points to the emacs24-nox command.  You need to install 'emacs24' instead, which removes emacs24-nox.

$ sudo update-alternatives --query emacs
Name: emacs
Link: /usr/bin/emacs
....
Status: auto
Best: /usr/bin/emacs24-nox
Value: /usr/bin/emacs24-nox

$ sudo apt install emacs24

$ sudo update-alternatives --query emacs
Name: emacs
Link: /usr/bin/emacs
...
Status: auto
Best: /usr/bin/emacs24-x
Value: /usr/bin/emacs24-x

Make sure that $DISPLAY is set correctly.

export DISPLAY=localhost:0.0


问:
Why AWS Cloudfront not classifying Tablet device as Tablet?
Below is the Lambda code I have.

When I hit the lambda, I could either get 'Desktop' or 'Mobile'. When I send a Tablet UserAgent, it is not classifying it as Tablet.

```<code>exports.handler = (event, context, callback) => {
    var region = process.env.AWS_REGION ? process.env.AWS_REGION : 'us-east-1';
    console.log(region);
    console.log(event);

    var device = {};
    if( event.headers['CloudFront-Is-Mobile-Viewer']  === "true" )
         device.device = 'Mobile';
    else if ( event.headers['CloudFront-Is-Tablet-Viewer']  === "true" )
         device.device = 'Tablet';
     else
         device.device = 'Desktop';

     var response = {
        statusCode: 200,
        body: JSON.stringify(device)
    };

    callback(null, response);
};
</code>```

I did double checked the headers received to lambda as well.

```<code>'CloudFront-Is-Desktop-Viewer': 'true',
'CloudFront-Is-Mobile-Viewer': 'false',
'CloudFront-Is-SmartTV-Viewer': 'false',
'CloudFront-Is-Tablet-Viewer': 'false',
'CloudFront-Viewer-Country': 'US',
</code>```

User-Agent:

Mozilla/5.0 (iPad; CPU OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B410 Safari/600.1.4

答:
Based on the value of the User-Agent header, CloudFront sets the value of these headers to true or false before forwarding the request to your origin. If a device falls into more than one category, more than one value might be true. For example, for some tablet devices, CloudFront might set both CloudFront-Is-Mobile-Viewer and CloudFront-Is-Tablet-Viewer to true. (emphasis added)

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-device

So if you are down-converting these to a single device categorization, you are likely to get the most sensible result if you test them in this order, stopping on the first match:

```<code>CloudFront-Is-SmartTV-Viewer
CloudFront-Is-Tablet-Viewer
CloudFront-Is-Mobile-Viewer
CloudFront-Is-Desktop-Viewer
</code>```

Body:
Below is the Lambda code I have.

When I hit the lambda, I could either get 'Desktop' or 'Mobile'. When I send a Tablet UserAgent, it is not classifying it as Tablet.

exports.handler = (event, context, callback) => {
    var region = process.env.AWS_REGION ? process.env.AWS_REGION : 'us-east-1';
    console.log(region);
    console.log(event);

    var device = {};
    if( event.headers['CloudFront-Is-Mobile-Viewer']  === "true" )
         device.device = 'Mobile';
    else if ( event.headers['CloudFront-Is-Tablet-Viewer']  === "true" )
         device.device = 'Tablet';
     else
         device.device = 'Desktop';

     var response = {
        statusCode: 200,
        body: JSON.stringify(device)
    };

    callback(null, response);
};

I did double checked the headers received to lambda as well.

'CloudFront-Is-Desktop-Viewer': 'true',
'CloudFront-Is-Mobile-Viewer': 'false',
'CloudFront-Is-SmartTV-Viewer': 'false',
'CloudFront-Is-Tablet-Viewer': 'false',
'CloudFront-Viewer-Country': 'US',

User-Agent:

Mozilla/5.0 (iPad; CPU OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B410 Safari/600.1.4

Body:
Based on the value of the User-Agent header, CloudFront sets the value of these headers to true or false before forwarding the request to your origin. If a device falls into more than one category, more than one value might be true. For example, for some tablet devices, CloudFront might set both CloudFront-Is-Mobile-Viewer and CloudFront-Is-Tablet-Viewer to true. (emphasis added)

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-device

So if you are down-converting these to a single device categorization, you are likely to get the most sensible result if you test them in this order, stopping on the first match:

CloudFront-Is-SmartTV-Viewer
CloudFront-Is-Tablet-Viewer
CloudFront-Is-Mobile-Viewer
CloudFront-Is-Desktop-Viewer


问:
Cannot upgrade pip from 1.5.4 to latest version
I am running ubuntu gnome 14.04 and have pip 1.5.4 installed for both python 2.7.6 and python 3.4.3.

I want to upgrade pip to the latest version but when I run the command
 pip install -U pip I get the following error .

```<code>Downloading/unpacking pip from https://pypi.python.org/packages/b6/ac/7015eb97dc749283ffdec1c3a88ddb8ae03b8fad0f0e611408f196358da3/pip-9.0.1-py2.py3-none-any.whl#md5=297dbd16ef53bcef0447d245815f5144
  Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB): 1.3MB downloaded
Installing collected packages: pip
  Found existing installation: pip 1.5.4
    Not uninstalling pip at /usr/lib/python2.7/dist-packages, owned by OS
  Can't roll back pip; was not uninstalled
Cleaning up...
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 672, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 902, in move_wheel_files
    pycompile=self.pycompile,
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 206, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 193, in clobber
    os.makedirs(destsubdir)
  File "/usr/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/pip'

Storing debug log for failure in /tmp/tmpDLrBk_
</code>```

On using sudo , i.e ;

sudo pip install -U pip

error -

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
python-pip is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 58 not upgraded.
alzio@alzio-HP-Pavilion-Notebook:/$ sudo -H pip install --upgrade pip
Cannot fetch index base URL https://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement pip in /usr/lib/python2.7/dist-packages
Downloading/unpacking pip
Cleaning up...
No distributions at all found for pip in /usr/lib/python2.7/dist-packages
Storing debug log for failure in /root/.pip/pip.log
</code>```

答:
I had the same problem. I backed up my pip installation using

```<code>sudo mv /usr/lib/python2.7/dist-packages/pip* .
sudo mv /usr/local/lib/python2.7/dist-packages/pip local_pip
</code>```

I then downloaded a bootstrap script and executed it:

```<code>wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py
</code>```

You can confirm that pip successfully upgraded by executing

```<code>pip -V
</code>```

I got the bootstrap link from pypa. I would appreciate feedback as I'm pretty sure this can be simplified, but resetting my pip version might be tricky.

Body:
I am running ubuntu gnome 14.04 and have pip 1.5.4 installed for both python 2.7.6 and python 3.4.3.

I want to upgrade pip to the latest version but when I run the command
 pip install -U pip I get the following error .

Downloading/unpacking pip from https://pypi.python.org/packages/b6/ac/7015eb97dc749283ffdec1c3a88ddb8ae03b8fad0f0e611408f196358da3/pip-9.0.1-py2.py3-none-any.whl#md5=297dbd16ef53bcef0447d245815f5144
  Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB): 1.3MB downloaded
Installing collected packages: pip
  Found existing installation: pip 1.5.4
    Not uninstalling pip at /usr/lib/python2.7/dist-packages, owned by OS
  Can't roll back pip; was not uninstalled
Cleaning up...
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 672, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 902, in move_wheel_files
    pycompile=self.pycompile,
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 206, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 193, in clobber
    os.makedirs(destsubdir)
  File "/usr/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/pip'

Storing debug log for failure in /tmp/tmpDLrBk_

On using sudo , i.e ;

sudo pip install -U pip

error -

Reading package lists... Done
Building dependency tree
Reading state information... Done
python-pip is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 58 not upgraded.
alzio@alzio-HP-Pavilion-Notebook:/$ sudo -H pip install --upgrade pip
Cannot fetch index base URL https://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement pip in /usr/lib/python2.7/dist-packages
Downloading/unpacking pip
Cleaning up...
No distributions at all found for pip in /usr/lib/python2.7/dist-packages
Storing debug log for failure in /root/.pip/pip.log

Body:
I had the same problem. I backed up my pip installation using

sudo mv /usr/lib/python2.7/dist-packages/pip* .
sudo mv /usr/local/lib/python2.7/dist-packages/pip local_pip

I then downloaded a bootstrap script and executed it:

wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py

You can confirm that pip successfully upgraded by executing

pip -V

I got the bootstrap link from pypa. I would appreciate feedback as I'm pretty sure this can be simplified, but resetting my pip version might be tricky.


问:
How to extract variable from script tag in html blob
I am trying to figure out how to extract a variable from a giant string of html. A simplified example is below:

Update Here is a screen shot of trying to use the common approach called out below. Doing something as simple as test['foo'] doesn't work. This is a string returned from a server and is never loaded into the actual document or window. It's just an html object that's kept in memory.

https://jsfiddle.net/hvpvg3o4/

HTML

```<code><div id="test"> <!-- div is just for jsfiddle -->
  <script>
    var test = { // <-- I WANT YOU!
      foo: 'bar'
    };

    var somethingIDontWant = 1;
    var iDontCareAboutYouEither = {
        blag: 1 + 1
    };
  </script>
</div>
</code>```

JavaScript

```<code>var testTag = document.getElementById('test');
var scriptTag = testTag.getElementsByTagName('script');
// var testObj = ?;
</code>```

I was hoping that I could just get the text from the script tag and either run eval or some JSON.parse, but since there's other stuff within the script tag, I can't

Is there some way to extract a variable from a script tag or some fancy regex to do so?

答:
Try this

console.log(test['foo'])
console.log(somethingIDontWant)
console.log(iDontCareAboutYouEither['blag'])```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test">
  <script>
    var test = {
      foo: 'bar'
    };

    var somethingIDontWant = 1;
    var iDontCareAboutYouEither = {
      blag: 1 + 1
    };
  </script>
</div></code>```

Body:
I am trying to figure out how to extract a variable from a giant string of html. A simplified example is below:

Update Here is a screen shot of trying to use the common approach called out below. Doing something as simple as test['foo'] doesn't work. This is a string returned from a server and is never loaded into the actual document or window. It's just an html object that's kept in memory.

https://jsfiddle.net/hvpvg3o4/

HTML

JavaScript

var testTag = document.getElementById('test');
var scriptTag = testTag.getElementsByTagName('script');
// var testObj = ?;

I was hoping that I could just get the text from the script tag and either run eval or some JSON.parse, but since there's other stuff within the script tag, I can't

Is there some way to extract a variable from a script tag or some fancy regex to do so?

Body:
Try this

console.log(test['foo'])
console.log(somethingIDontWant)
console.log(iDontCareAboutYouEither['blag'])

<div id="test">
  <script>
    var test = {
      foo: 'bar'
    };

    var somethingIDontWant = 1;
    var iDontCareAboutYouEither = {
      blag: 1 + 1
    };
  </script>
</div>


问:
How to save key corresponding to every value of a dictionary in a list in Python?
I have a dictionary which has only two keys: "f" and "m". Both these keys have 1000 unique values in it. Therefore total 2000 values corresponding to "f" and "m"

How can create a list of length 2000 having key's stored in it i.e. "f" and "m" for all 2000 values of dict ?

Edit: I wanted output to be a list like ['f','f','f',........(1000 "f" in list ),'m','m'.......(1000 "m" in list)]

答:
Let's create/simulate a dictionary 'foo' containing 2 keys 'f' and 'm'. The value stored against each of these keys is a list of 1000 elements.

```<code>>>> foo = {'f': ['x']*1000, 'm': ['y']*1000}
>>> len(foo['f'])
1000
>>> len(foo['m'])
1000
>>>
</code>```

Now, let's initialize an empty list 'bar' to store the desired output.

```<code>>>> bar = []
>>>
</code>```

A list can be extended to include elements from other list in the original list. Let's use this to extend 'bar' to contain as many 'f' as the number of elements in foo['f'].

```<code>>>> bar.extend(['f']*len(foo['f']))
>>>
</code>```

Repeat the same for foo['m']

```<code>>>> bar.extend(['m']*len(foo['m']))
>>>
</code>```

Now, 'bar' is a list of 2000 elements - first 1000 elements are 'f' and next 1000 elements are 'm'. Verifying the values against indices 0, 999 (first 1000 elements) and 1000, 1999 (remaining 1000 elements) prove the same.

```<code>>>> len(bar)
2000
>>> bar[0]
'f'
>>> bar[999]
'f'
>>> bar[1000]
'm'
>>> bar[1999]
'm'
>>>
</code>```

Body:
Let's create/simulate a dictionary 'foo' containing 2 keys 'f' and 'm'. The value stored against each of these keys is a list of 1000 elements.

>>> foo = {'f': ['x']*1000, 'm': ['y']*1000}
>>> len(foo['f'])
1000
>>> len(foo['m'])
1000
>>>

Now, let's initialize an empty list 'bar' to store the desired output.

>>> bar = []
>>>

A list can be extended to include elements from other list in the original list. Let's use this to extend 'bar' to contain as many 'f' as the number of elements in foo['f'].

>>> bar.extend(['f']*len(foo['f']))
>>>

Repeat the same for foo['m']

>>> bar.extend(['m']*len(foo['m']))
>>>

Now, 'bar' is a list of 2000 elements - first 1000 elements are 'f' and next 1000 elements are 'm'. Verifying the values against indices 0, 999 (first 1000 elements) and 1000, 1999 (remaining 1000 elements) prove the same.

>>> len(bar)
2000
>>> bar[0]
'f'
>>> bar[999]
'f'
>>> bar[1000]
'm'
>>> bar[1999]
'm'
>>>


Title: How to save key corresponding to every value of a dictionary in a list in Python?

Body:
I have a dictionary which has only two keys: "f" and "m". Both these keys have 1000 unique values in it. Therefore total 2000 values corresponding to "f" and "m"

How can create a list of length 2000 having key's stored in it i.e. "f" and "m" for all 2000 values of dict ?

Edit: I wanted output to be a list like ['f','f','f',........(1000 "f" in list ),'m','m'.......(1000 "m" in list)]

Body:
do you want something like this ?

dummy_dict={'f':[1,2,3,4,5,6],'m':[14,13,11,43,11,2,11,1,4,34]}

print([key for key,value in dummy_dict.items() for _ in range(len(value))])

output :

['f', 'f', 'f', 'f', 'f', 'f', 'm', 'm', 'm', 'm', 'm', 'm', 'm', 'm', 'm', 'm']


问:
submitting form to controller@store
laravel 5.5

 voyager 1.0

i'm trying to submit a form to a controller with :

```<code><form class="" action="FeedController@store" method="post">
    <div class="mui-textfield mui-textfield--float-label">
        <input id="title" type="text"  name="title" value="" required autofocus>
        <label for="title" class="col-md-4 control-label">title</label>
    </div>
    <div class="mui-textfield mui-textfield--float-label">
        <textarea id="description" type="textarea"  name="description" value="" required autofocus></textarea>
        <label for="description" class="col-md-4 control-label">description</label>
    </div>
    <input class="mui-btn btn-primary pull-right " type="submit" name="" value="submit">
</form>
</code>```

within FeedController:

```<code>/**
*@param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request){

    $data = ReportDatum::create([
        'owner_id' => auth()->id(),
        'title' => request('title'),
        'description' => request('description')
    ]);
    return test;
}
</code>```

and in the routes:

```<code>Route::resource('feed', 'FeedController');
</code>```

(and/or depending on what I'm trying)

```<code> Route::post('store', 'FeedController@store');
</code>```

what I'm i missing to correctly submit the form?

  I'm not using laravelCollective forms

答:
You should define route at first then it will works:
Resource controller routing

```<code>Route::resource('feed', 'FeedController');
</code>```

or specific simple routing

```<code>Route::post('feed', 'FeedController@store');
</code>```

Title: submitting form to controller@store

Body:
laravel 5.5

 voyager 1.0

i'm trying to submit a form to a controller with :

<form class="" action="FeedController@store" method="post">

        <input id="title" type="text"  name="title" value="" required autofocus>
        title

        <textarea id="description" type="textarea"  name="description" value="" required autofocus></textarea>
        description

    <input class="mui-btn btn-primary pull-right " type="submit" name="" value="submit">
</form>

within FeedController:

/**
*@param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request){

    $data = ReportDatum::create([
        'owner_id' => auth()->id(),
        'title' => request('title'),
        'description' => request('description')
    ]);
    return test;
}

and in the routes:

Route::resource('feed', 'FeedController');

(and/or depending on what I'm trying)

 Route::post('store', 'FeedController@store');

what I'm i missing to correctly submit the form?

  I'm not using laravelCollective forms

Body:
You should define route at first then it will works:
Resource controller routing

Route::resource('feed', 'FeedController');

or specific simple routing

Route::post('feed', 'FeedController@store');


问:
Select onchange, trying run script to load separate text into 2 textareas
I have a table and within it is a set of select values which auto populate a textarea based on which of the options is selected. What I am trying to do is make it populate two pieces of information into separate text areas when an option is chosen, The first being text into Bar_green and the second being a URL into Top_green2. Is this possible?  I just can't wrap my brain around this. Here is the code I am using:</p>

```<code><html>
<head>
<title></title>
<HTA:APPLICATION id="" applicationname="" border="thick" caption="yes" icon="c:\windows\system32\write.exe" showintaskbar="yes" singleinstance="no" sysmenu="yes" windowstate="normal" contextmenu="yes">
<style>

</style>
</head>
<body>

<table border=0 cellpadding=0 cellspacing=0 height="100%" width="100%">
<tr>

<td class="top_area" id="top_green">

<script type="text/javascript">
        function showText_green(){
           var value = document.getElementById('options_green').value;
           if(value != ""){
             document.getElementById('bar_green').innerHTML = value;
             document.getElementById('bar_green').style.display = "block";
           }
        }
    </script>

<!--<script type="text/javascript">
        function showLink_green(){
           var value = document.getElementById('options_green').value;
           if(value != ""){
             document.getElementById('top_green2').innerHTML = value;
             document.getElementById('top_green2').style.display = "block";
           }
        }-->
    </script>
        <select id="options_green" onchange="showText_green(); showLink_green()">
            <option value="">Select an option</option>
            <option value="text 1">Option 1</option>
            <option value="text 2">Option 2</option>
            <option value="text 3">Option 3</option>
            <option value="text 4">Option 4</option>
            <option value="text 5">Option 5</option>
            <option value="text 6">Option 6</option>
            <option value="text 7">Option 7</option>
       </select>

</td>

    <tr>
        <td class="top_area2"><textarea id="top_green2"></textarea></td>
    </tr>
        <td class="bar_area"><textarea id="bar_green"></textarea></td>
    </tr>
</table>

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

答:
You can do this with simple JQuery. And for text and URL, you can use custom attributes and data() in JQuery. Below is the snippet:.

$("#options_green").on('change', function() {
  $("#top_green2").val($(this).val());
  $("#bar_green").val($(this).find('option:selected').data('url'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=0 cellpadding=0 cellspacing=0 height="100%" width="100%">
  <tr>

    <td class="top_area" id="top_green">

      <select id="options_green">
            <option value="">Select an option</option>
            <option value="text 1" data-url="url-1">Option 1</option>
            <option value="text 2" data-url="url-2">Option 2</option>
            <option value="text 3" data-url="url-3">Option 3</option>
            <option value="text 4" data-url="url-4">Option 4</option>
            <option value="text 5" data-url="url-5">Option 5</option>
            <option value="text 6" data-url="url-6">Option 6</option>
            <option value="text 7" data-url="url-7">Option 7</option>
       </select>

    </td>
  </tr>
  <tr>
    <td class="top_area2"><textarea id="top_green2"></textarea></td>
  </tr>
  <tr>
    <td class="bar_area"><textarea id="bar_green"></textarea></td>
  </tr>
</table></code>```

Body:
I have a table and within it is a set of select values which auto populate a textarea based on which of the options is selected. What I am trying to do is make it populate two pieces of information into separate text areas when an option is chosen, The first being text into Bar_green and the second being a URL into Top_green2. Is this possible?  I just can't wrap my brain around this. Here is the code I am using:

<title></title>
<HTA:APPLICATION id="" applicationname="" border="thick" caption="yes" icon="c:\windows\system32\write.exe" showintaskbar="yes" singleinstance="no" sysmenu="yes" windowstate="normal" contextmenu="yes">

Body:
You can do this with simple JQuery. And for text and URL, you can use custom attributes and data() in JQuery. Below is the snippet:.

$("#options_green").on('change', function() {
  $("#top_green2").val($(this).val());
  $("#bar_green").val($(this).find('option:selected').data('url'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=0 cellpadding=0 cellspacing=0 height="100%" width="100%">
  <tr>

    <td class="top_area" id="top_green">

      <select id="options_green">
            <option value="">Select an option</option>
            <option value="text 1" data-url="url-1">Option 1</option>
            <option value="text 2" data-url="url-2">Option 2</option>
            <option value="text 3" data-url="url-3">Option 3</option>
            <option value="text 4" data-url="url-4">Option 4</option>
            <option value="text 5" data-url="url-5">Option 5</option>
            <option value="text 6" data-url="url-6">Option 6</option>
            <option value="text 7" data-url="url-7">Option 7</option>
       </select>

    </td>
  </tr>
  <tr>
    <td class="top_area2"><textarea id="top_green2"></textarea></td>
  </tr>
  <tr>
    <td class="bar_area"><textarea id="bar_green"></textarea></td>
  </tr>
</table>


问:
How do I increase the video memory in VMWare Workstation for OS X 10.12?
I'm using VMWare Workstation 12 to run OS X 10.12 from Windows 10 Home. I have an NVidia GeForce GTX 960M with 2 GB dedicated video memory. I don't see a setting in the virtual machine setting that allows me to change the amount of video memory allotted to the guest. If I remember correctly I think I maxed it out at 128 MB during the setup. Can someone help me figure out how to give the guest more video memory?</p>

答: Apparently this isn't an option on workstation.</p>


问:
CSS Translate and Scale on Y-Axis?
I am taking an online course learning CSS and we are just covering CSS animations. I am trying to practice some of the things I learned (just basic transforms for now) by creating a small animation of a man walking towards the screen down a pathway.

Basically, I want to both translate and scale my image at the same time. I got this working fine, but now I also wanted to add some small rotation so that it looks like the man is slightly moving left and right. Here is my code in a jsfiddle, I don't know how to change the transform-origin so that the man is walking in a straight line on the Y-Axis, the scale makes him walk in a diagonal. I hope that makes sense...

The commented out part of the code includes the scale, as soon as that is added back, and the part without scale is commented out, it acts funny and I'm thinking this has to do with the origin?

https://jsfiddle.net/qLLqdxbm/

HTML:

```<code><div class="man-scale">
  <img class="man-walk" src="http://clipart-library.com/img/1184697.png">
</div>
</code>```

CSS:

```<code>.man-walk {
    width: 100px;
    height: 125px;
    position: absolute;
    top: 0;
    left: 50px;

    animation-name: man-walk;
    animation-duration: 0.45s;
    animation-iteration-count: infinite;
}

@keyframes man-walk {
    0% {
        transform: rotate(0deg);
    }

    25% {
        transform: rotate(1.5deg);
    }

    50% {
        transform: rotate(0deg);
    }

    75% {
        transform: rotate(-1.5deg);
    }

    100% {
        transform: rotate(0deg);
    }
}

.man-scale {
    width: 100px;
    height: 125px;

    animation-name: man-scale;
    animation-duration: 2s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

/* define the animation */
@keyframes man-scale {
/*     0% {
        transform: translate(0px, 5px) scale(1.1);
    }

    25% {
        transform: translate(0px, 15px) scale(1.5);
    }

    50% {
        transform: translate(0px, 25px) scale(1.7);
    }

    75% {
        transform: translate(0px, 35px) scale(2.0);
    }

    100% {
        transform: translate(0px, 45px) scale(2.3);
    } */

    0% {
        transform: translate(0px, 5px);
    }

    25% {
        transform: translate(0px, 15px);
    }

    50% {
        transform: translate(0px, 25px);
    }

    75% {
        transform: translate(0px, 35px);
    }

    100% {
        transform: translate(0px, 45px);
    }
}
</code>```

Thanks for the help!

答:
Each time you scale the image along X and Y, the origin shifts in both dimensions by a specific offset. If you can compensate for that offset in the X dimension then a vertical animation could be achieved.

In this case in first keyframe the scale increased by 0.1 which is 100 * 0.1 = 10px now origin got offset by 5px in X dimension, compensating in terms of translateX(-5px). Similarly for all the other keyframes.

If you want a faster animation in the Y dimension just increase the Y translate values without touching the X translation values.

.man-walk {
    width: 100px;
    height: 125px;
    position: absolute;
    top: 0;
    left: 50px;

    animation-name: man-walk;
    animation-duration: 0.45s;
    animation-iteration-count: infinite;
}

@keyframes man-walk {
    0% {
        transform: rotate(0deg);
    }

    25% {
        transform: rotate(1.5deg);
    }

    50% {
        transform: rotate(0deg);
    }

    75% {
        transform: rotate(-1.5deg);
    }

    100% {
        transform: rotate(0deg);
    }
}

.man-scale {
    width: 100px;
    height: 125px;

    animation-name: man-scale;
    animation-duration: 2s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

/* define the animation */
@keyframes man-scale {
     0% {
        transform: translate(-5px, 30px) scale(1.1);
    }

    25% {
        transform: translate(-20px, 70px) scale(1.4);
    }

    50% {
        transform: translate(-35px, 120px) scale(1.7);
    }

    75% {
        transform: translate(-50px, 180px) scale(2.0);
    }

    100% {
        transform: translate(-65px, 250px) scale(2.3);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="man-scale">
  <img class="man-walk" src="http://clipart-library.com/img/1184697.png">
</div></code>```

There might be some advanced CSS techniques to calculate the offset automatically.

Title: CSS Translate and Scale on Y-Axis?

Body:
I am taking an online course learning CSS and we are just covering CSS animations. I am trying to practice some of the things I learned (just basic transforms for now) by creating a small animation of a man walking towards the screen down a pathway.

Basically, I want to both translate and scale my image at the same time. I got this working fine, but now I also wanted to add some small rotation so that it looks like the man is slightly moving left and right. Here is my code in a jsfiddle, I don't know how to change the transform-origin so that the man is walking in a straight line on the Y-Axis, the scale makes him walk in a diagonal. I hope that makes sense...

The commented out part of the code includes the scale, as soon as that is added back, and the part without scale is commented out, it acts funny and I'm thinking this has to do with the origin?

https://jsfiddle.net/qLLqdxbm/

HTML:

CSS:

.man-walk {
    width: 100px;
    height: 125px;
    position: absolute;
    top: 0;
    left: 50px;

    animation-name: man-walk;
    animation-duration: 0.45s;
    animation-iteration-count: infinite;
}

@keyframes man-walk {
    0% {
        transform: rotate(0deg);
    }

    25% {
        transform: rotate(1.5deg);
    }

    50% {
        transform: rotate(0deg);
    }

    75% {
        transform: rotate(-1.5deg);
    }

    100% {
        transform: rotate(0deg);
    }
}

.man-scale {
    width: 100px;
    height: 125px;

    animation-name: man-scale;
    animation-duration: 2s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

/* define the animation */
@keyframes man-scale {
/*     0% {
        transform: translate(0px, 5px) scale(1.1);
    }

    25% {
        transform: translate(0px, 15px) scale(1.5);
    }

    50% {
        transform: translate(0px, 25px) scale(1.7);
    }

    75% {
        transform: translate(0px, 35px) scale(2.0);
    }

    100% {
        transform: translate(0px, 45px) scale(2.3);
    } */

    0% {
        transform: translate(0px, 5px);
    }

    25% {
        transform: translate(0px, 15px);
    }

    50% {
        transform: translate(0px, 25px);
    }

    75% {
        transform: translate(0px, 35px);
    }

    100% {
        transform: translate(0px, 45px);
    }
}

Thanks for the help!

Body:
Each time you scale the image along X and Y, the origin shifts in both dimensions by a specific offset. If you can compensate for that offset in the X dimension then a vertical animation could be achieved.

In this case in first keyframe the scale increased by 0.1 which is 100 * 0.1 = 10px now origin got offset by 5px in X dimension, compensating in terms of translateX(-5px). Similarly for all the other keyframes.

If you want a faster animation in the Y dimension just increase the Y translate values without touching the X translation values.

.man-walk {
    width: 100px;
    height: 125px;
    position: absolute;
    top: 0;
    left: 50px;

    animation-name: man-walk;
    animation-duration: 0.45s;
    animation-iteration-count: infinite;
}

@keyframes man-walk {
    0% {
        transform: rotate(0deg);
    }

    25% {
        transform: rotate(1.5deg);
    }

    50% {
        transform: rotate(0deg);
    }

    75% {
        transform: rotate(-1.5deg);
    }

    100% {
        transform: rotate(0deg);
    }
}

.man-scale {
    width: 100px;
    height: 125px;

    animation-name: man-scale;
    animation-duration: 2s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

/* define the animation */
@keyframes man-scale {
     0% {
        transform: translate(-5px, 30px) scale(1.1);
    }

    25% {
        transform: translate(-20px, 70px) scale(1.4);
    }

    50% {
        transform: translate(-35px, 120px) scale(1.7);
    }

    75% {
        transform: translate(-50px, 180px) scale(2.0);
    }

    100% {
        transform: translate(-65px, 250px) scale(2.3);
    }
}

<div class="man-scale">
  <img class="man-walk" src="http://clipart-library.com/img/1184697.png">
</div>

There might be some advanced CSS techniques to calculate the offset automatically.


问:
media query for scrolling slideshow for display on different size devices
I want to create a media query for a scrolling slideshow so that the images display at their native resolution of 960x540 px on a 1920x1080 monitor; but at 768x432 on a 1366x768 monitor.  I tried plugging in the recomputed values of the keyframes for the smaller screen in the media query but it did not work.

If anyone can help I'd be most appreciative as I have not worked extensively with media queries or animations.  Hopefully, I can extrapolate from an answer to further modify the slideshow for smaller devices too.

```<code><!DOCTYPE HTML>
<html>
<head>
    <style>
.wrapper_video_and_text {
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    width: 100%;
    padding-top: 0px;
    justify-content: center;
    }
.container_video {
    width: 55%;
    margin-left: 100px;
    }
.wrapper_text {
    display: flex;
    width: 45%;
    overflow: hidden;
    min-height: 100%;
    justify-content: center;
    align-items: center;
    }
.video_text {
    width: 50%;
    font-family: "europa",sans-serif;
    font-size: 150%;
    letter-spacing: ;
    color: black;
    font-weight: 500;
    line-height: 125%;
    }
.flex-container {
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    width: 100%;
    padding-top: 0px;
    justify-content: center;
    align-items: center;
    }
#css_slider {
    width: 960px;
    height: 540px;
    overflow: hidden;
}
#slider_images {
    width : 12480px;
    height: 540px;
    overflow: hidden;
    /* animation duration: 36s : 13x ~3s display image + 5x ~0.2s slide */
    animation: slide 36s infinite;
    -moz-animation: slide 36s infinite;
    -webkit-animation: slide 36s infinite;
    -o-animation: slide 36s infinite;
}
#slider_images img {
    float: left;
}
    @keyframes slide{
    0%{margin-left: 0px;}
    4.7%{margin-left: 0px;}
    7.7%{margin-left: -960px;}
    12.4%{margin-left: -960px;}
    15.4%{margin-left: -1920px;}
    20.1%{margin-left: -1920px;}
    23.1%{margin-left: -2880px;}
    27.8%{margin-left: -2880px;}
    30.8%{margin-left: -3840px;}
    35.5%{margin-left: -3840px;}
    38.5%{margin-left: -4800px;}
    43.2%{margin-left: -4800px;}
    46.2%{margin-left: -5760px;}
    50.9%{margin-left: -5760px;}
    53.9%{margin-left: -6720px;}
    58.6%{margin-left: -6720px;}
    61.6%{margin-left: -7680px;}
    66.3%{margin-left: -7680px;}
    69.3%{margin-left: -8640px;}
    74%{margin-left: -8640px;}
    77%{margin-left: -9600px;}
    81.7%{margin-left: -9600px;}
    84.7%{margin-left: -10560px;}
    89.4%{margin-left: -10560px;}
    92.4%{margin-left: -11520px;}
    97.1%{margin-left: -11520px;}
    100%{margin-left: 0px;}
}
    @-moz-keyframes slide{
    0%{margin-left: 0px;}
    4.7%{margin-left: 0px;}
    7.7%{margin-left: -960px;}
    12.4%{margin-left: -960px;}
    15.4%{margin-left: -1920px;}
    20.1%{margin-left: -1920px;}
    23.1%{margin-left: -2880px;}
    27.8%{margin-left: -2880px;}
    30.8%{margin-left: -3840px;}
    35.5%{margin-left: -3840px;}
    38.5%{margin-left: -4800px;}
    43.2%{margin-left: -4800px;}
    46.2%{margin-left: -5760px;}
    50.9%{margin-left: -5760px;}
    53.9%{margin-left: -6720px;}
    58.6%{margin-left: -6720px;}
    61.6%{margin-left: -7680px;}
    66.3%{margin-left: -7680px;}
    69.3%{margin-left: -8640px;}
    74%{margin-left: -8640px;}
    77%{margin-left: -9600px;}
    81.7%{margin-left: -9600px;}
    84.7%{margin-left: -10560px;}
    89.4%{margin-left: -10560px;}
    92.4%{margin-left: -11520px;}
    97.1%{margin-left: -11520px;}
    100%{margin-left: 0px;}
}
@-webkit-keyframes slide{
    0%{margin-left: 0px;}
    4.7%{margin-left: 0px;}
    7.7%{margin-left: -960px;}
    12.4%{margin-left: -960px;}
    15.4%{margin-left: -1920px;}
    20.1%{margin-left: -1920px;}
    23.1%{margin-left: -2880px;}
    27.8%{margin-left: -2880px;}
    30.8%{margin-left: -3840px;}
    35.5%{margin-left: -3840px;}
    38.5%{margin-left: -4800px;}
    43.2%{margin-left: -4800px;}
    46.2%{margin-left: -5760px;}
    50.9%{margin-left: -5760px;}
    53.9%{margin-left: -6720px;}
    58.6%{margin-left: -6720px;}
    61.6%{margin-left: -7680px;}
    66.3%{margin-left: -7680px;}
    69.3%{margin-left: -8640px;}
    74%{margin-left: -8640px;}
    77%{margin-left: -9600px;}
    81.7%{margin-left: -9600px;}
    84.7%{margin-left: -10560px;}
    89.4%{margin-left: -10560px;}
    92.4%{margin-left: -11520px;}
    97.1%{margin-left: -11520px;}
    100%{margin-left: 0px;}
}
 @-o-keyframes slide{
    0%{margin-left: 0px;}
    4.7%{margin-left: 0px;}
    7.7%{margin-left: -960px;}
    12.4%{margin-left: -960px;}
    15.4%{margin-left: -1920px;}
    20.1%{margin-left: -1920px;}
    23.1%{margin-left: -2880px;}
    27.8%{margin-left: -2880px;}
    30.8%{margin-left: -3840px;}
    35.5%{margin-left: -3840px;}
    38.5%{margin-left: -4800px;}
    43.2%{margin-left: -4800px;}
    46.2%{margin-left: -5760px;}
    50.9%{margin-left: -5760px;}
    53.9%{margin-left: -6720px;}
    58.6%{margin-left: -6720px;}
    61.6%{margin-left: -7680px;}
    66.3%{margin-left: -7680px;}
    69.3%{margin-left: -8640px;}
    74%{margin-left: -8640px;}
    77%{margin-left: -9600px;}
    81.7%{margin-left: -9600px;}
    84.7%{margin-left: -10560px;}
    89.4%{margin-left: -10560px;}
    92.4%{margin-left: -11520px;}
    97.1%{margin-left: -11520px;}
    100%{margin-left: 0px;}
    }
    </style>
    </head>
 <section class="flex-container">
    <div id="css_slider">
     <!-- Each image is 960px by 540px -->
    <div id="slider_images">
        <img src="web_960_lg_edg_water.jpg" alt="water" />
        <img src="web_960_lg_edg_blue.jpg" alt="blue" />
        <img src="web_960_lg_edg_robins_egg.jpg" alt="robins egg" />
        <img src="web_960_lg_edg_23rd_st.jpg" alt="23rd st" />
        <img src="web_960_lg_edg_broken_guru.jpg" alt="broken guru" />
        <img src="web_960_lg_edg_i_will_miss_you.jpg" alt="i will miss you" />
        <img src="web_960_lg_edg_pants.jpg" alt="pants" />
        <img src="web_960_lg_edg_nose.jpg" alt="nose" />
        <img src="web_960_lg_edg_swirls.jpg" alt="swirls" />
        <img src="web_960_lg_edg_church_ave.jpg" alt="church ave" />
        <img src="web_960_lg_edg_network_reality_stars.jpg" alt="network reality all stars" />
        <img src="web_960_lg_edg_ports.jpg" alt="ports" />
        <img src="web_960_lg_edg_kline.jpg" alt="kline" />
    </div>
    </div>
       <div class="wrapper_text">
        <div class="video_text">
        <p>text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here </p>
        </div>
    </div>
</section>
</html>
</code>```

答:
I am going to try and help, as I am still learning here but I believe you will need to define the media queries and the properties for the selectors you are calling on. Also if you want the elements to stack on top of each other remove the floats if present.

Go with something like this and repeat. Let me know if it works. Thanks

```<code>/* Media Queries */
@media screen and (max-width: 432px) , screen and (max-height: 768px) {
#slider_images {
width: 1920px;
height: 1080px;
</code>```

}

Body:
I want to create a media query for a scrolling slideshow so that the images display at their native resolution of 960x540 px on a 1920x1080 monitor; but at 768x432 on a 1366x768 monitor.  I tried plugging in the recomputed values of the keyframes for the smaller screen in the media query but it did not work.

If anyone can help I'd be most appreciative as I have not worked extensively with media queries or animations.  Hopefully, I can extrapolate from an answer to further modify the slideshow for smaller devices too.

<!DOCTYPE HTML>

text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here

Body:
I am going to try and help, as I am still learning here but I believe you will need to define the media queries and the properties for the selectors you are calling on. Also if you want the elements to stack on top of each other remove the floats if present.

Go with something like this and repeat. Let me know if it works. Thanks

/* Media Queries */
@media screen and (max-width: 432px) , screen and (max-height: 768px) {
#slider_images {
width: 1920px;
height: 1080px;

}


问:
NSDate - one year ago, dilemma
I'm trying to do something that, for me, is a bit difficult. But I'm sure someone has some insight.

Given a date, say January 17, 2011, I'm trying to figure out the day that corresponds to this date one year ago. So January 17, 2011 is a Monday, and one year ago, this day fell on January 18, 2010 (a Monday as well). It turns out that January 18, 2010 is 354 days before January 17, 2011. I originally thought to just simply subtract 365 days for a non-leap year and 366 days for a leap year, but if you do that in this case, you would get January 17, 2010, which is a Sunday, not a Monday.

So, in Objective-C with NSDate and NSCalendar, how could I implement a function such as:

```<code>-(NSDate *)logicalOneYearAgo:(NSDate *)from {
}
</code>```

In other words, the nth "weekday" of the nth month (where "weekday" is Monday or Tuesday or Wednesday etc)

答:
You use NSDateComponents like so:</p>

```<code>- (NSDate *)logicalOneYearAgo:(NSDate *)from {

    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

    NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
    [offsetComponents setYear:-1];

    return [gregorian dateByAddingComponents:offsetComponents toDate:from options:0];

}
</code>```

Title: NSDate - one year ago, dilemma

Body:
I'm trying to do something that, for me, is a bit difficult. But I'm sure someone has some insight.

Given a date, say January 17, 2011, I'm trying to figure out the day that corresponds to this date one year ago. So January 17, 2011 is a Monday, and one year ago, this day fell on January 18, 2010 (a Monday as well). It turns out that January 18, 2010 is 354 days before January 17, 2011. I originally thought to just simply subtract 365 days for a non-leap year and 366 days for a leap year, but if you do that in this case, you would get January 17, 2010, which is a Sunday, not a Monday.

So, in Objective-C with NSDate and NSCalendar, how could I implement a function such as:

-(NSDate *)logicalOneYearAgo:(NSDate *)from {
}

In other words, the nth "weekday" of the nth month (where "weekday" is Monday or Tuesday or Wednesday etc)

Body:
You use NSDateComponents like so:

- (NSDate *)logicalOneYearAgo:(NSDate *)from {

    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

    NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
    [offsetComponents setYear:-1];

    return [gregorian dateByAddingComponents:offsetComponents toDate:from options:0];

}

ContentLicense: CC BY-SA 2.5


问:
Django /subdirectory/admin/ redirects to /admin/login/?next=/admin/
I set up a Django server on port 8011, and have a nginx serving it as a subdirectory on port 80.

Static files, good.

Pages, good.

But when I access /subdirectory/admin/, it takes me to: /admin/login/?next=/admin/

Which is of course a 404 error, but if I access /subdirectory/admin/login/?next=/admin/, it works fine.

Any ideas? Do I need to set a variable in the settings.py?

urls.py:

```<code>    url(r'^admin/', admin.site.urls),
</code>```

nginx config:

```<code>server {
    listen 80;

    location /sdc {
        proxy_pass http://127.0.0.1:8011/;
    }
}
</code>```

答:
I believe what is happening is that when django sees you aren't logged in, it redirects you to the url named 'admin:login'. It figures out that url by reversing what it sees in your urls.py, which is this case comes out to be admin/login/ (https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#reversing-admin-urls). This means it doesn't know it is operating within /subdirectory/.

Try add subdirectory in urls.py

```<code>url(r'^subdirectory/admin/', admin.site.urls),
</code>```

Body:
I set up a Django server on port 8011, and have a nginx serving it as a subdirectory on port 80.

Static files, good.

Pages, good.

But when I access /subdirectory/admin/, it takes me to: /admin/login/?next=/admin/

Which is of course a 404 error, but if I access /subdirectory/admin/login/?next=/admin/, it works fine.

Any ideas? Do I need to set a variable in the settings.py?

urls.py:

    url(r'^admin/', admin.site.urls),

nginx config:

server {
    listen 80;

    location /sdc {
        proxy_pass http://127.0.0.1:8011/;
    }
}

Body:
I believe what is happening is that when django sees you aren't logged in, it redirects you to the url named 'admin:login'. It figures out that url by reversing what it sees in your urls.py, which is this case comes out to be admin/login/ (https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#reversing-admin-urls). This means it doesn't know it is operating within /subdirectory/.

Try add subdirectory in urls.py

url(r'^subdirectory/admin/', admin.site.urls),


问:
How do I change x-axis from numeric to custom ggplot?
I have data that looks like:

```<code>require(ggplot2); require(lubridate); require(data.table); require(dplyr)

Date  <- rep(seq.Date(as.Date("2014-01-01"), as.Date("2016-12-31"), by = "days"), 3)
Index <- rep(c(rep(1:365, times = 2), 1:366), 3)
Counts<- sample(1:25, size = length(Index), replace = TRUE)
City  <- rep(c("Dallas", "San Antonio", "Houston"), each = length(Index)/3)

df    <- data.frame(Date = Date, Index = Index, Counts = Counts, City = City)

df    <- df %>% mutate(Year = year(as.Date(Date)))
</code>```

I graphed the data using the following code:

```<code>ggplot(df, aes(x = Index, y = Counts, colour = City)) +
  geom_line(aes(group = City))+
  geom_vline(xintercept = c(31, 59.5, 90, 120, 151, 181, 212, 243, 273, 304, 334))+
  facet_grid(Year~.) +
  theme(legend.position = "bottom")
</code>```

My goal is to actually label the x-axis as Jan Feb ... Dec. I have tried scale_x_continuous and scale_x_discrete with no avail. Any suggestions?

Thanks in advance

答:
I think this is easier to achieve if you use Date as your x variable and make use of scale_x_date:

```<code>df <- df %>% mutate(Year = year(as.Date(Date)),
                    MonthStart = round_date(Date, unit = "month"))

mid_months <- seq.Date(as.Date("2014-01-15"), as.Date("2016-12-15"), by = "months")

ggplot(df, aes(x = Date, y = Counts, colour = City)) +
    geom_line(aes(group = City))+
    facet_wrap(~ Year, ncol = 1, scales = "free") +
    geom_vline(aes(xintercept = MonthStart), colour = 'black') +
    # expand = c(0,0) to ensure scale doesn't extend to additional
    #   months
    scale_x_date(breaks = mid_months, date_labels = "%b", expand = c(0, 0)) +
    theme(legend.position = "bottom")
</code>```

EDIT: updated to add mid-month labels

Body:
I have data that looks like:

require(ggplot2); require(lubridate); require(data.table); require(dplyr)

Date  <- rep(seq.Date(as.Date("2014-01-01"), as.Date("2016-12-31"), by = "days"), 3)
Index <- rep(c(rep(1:365, times = 2), 1:366), 3)
Counts<- sample(1:25, size = length(Index), replace = TRUE)
City  <- rep(c("Dallas", "San Antonio", "Houston"), each = length(Index)/3)

df    <- data.frame(Date = Date, Index = Index, Counts = Counts, City = City)

df    <- df %>% mutate(Year = year(as.Date(Date)))

I graphed the data using the following code:

ggplot(df, aes(x = Index, y = Counts, colour = City)) +
  geom_line(aes(group = City))+
  geom_vline(xintercept = c(31, 59.5, 90, 120, 151, 181, 212, 243, 273, 304, 334))+
  facet_grid(Year~.) +
  theme(legend.position = "bottom")

My goal is to actually label the x-axis as Jan Feb ... Dec. I have tried scale_x_continuous and scale_x_discrete with no avail. Any suggestions?

Thanks in advance

Body:
I think this is easier to achieve if you use Date as your x variable and make use of scale_x_date:

df <- df %>% mutate(Year = year(as.Date(Date)),
                    MonthStart = round_date(Date, unit = "month"))

mid_months <- seq.Date(as.Date("2014-01-15"), as.Date("2016-12-15"), by = "months")

ggplot(df, aes(x = Date, y = Counts, colour = City)) +
    geom_line(aes(group = City))+
    facet_wrap(~ Year, ncol = 1, scales = "free") +
    geom_vline(aes(xintercept = MonthStart), colour = 'black') +
    # expand = c(0,0) to ensure scale doesn't extend to additional
    #   months
    scale_x_date(breaks = mid_months, date_labels = "%b", expand = c(0, 0)) +
    theme(legend.position = "bottom")

EDIT: updated to add mid-month labels


问:
How do you delete a completed task for a Delete-By-Query in Elasticsearch 5.6?
I currently have a completed delete-by-query task:

curl -XGET "http://localhost/_tasks/x0i0D1FdEs-M29DDewnPwkg:257894116"
  {"completed":true,"task":{"node":"x0i0D1FdEs-M29DDewnPwkg","id":257894116,"type":"transport","action":"indices:data/write/delete/byquery","status":{"total":2650620,"updated":0,"created":0,"deleted":2650620,"batches":2651,"version_conflicts":0,"noops":0,"retries":{"bulk":0,"search":0},"throttled_millis":0,"requests_per_second":-1.0,"throttled_until_millis":0},"description":"delete-by-query [testIndex]","start_time_in_millis":1509555456799,"running_time_in_nanos":386994755521,"cancellable":true},"response":{"took":386993,"timed_out":false,"total":2650620,"updated":0,"created":0,"deleted":2650620,"batches":2651,"version_conflicts":0,"noops":0,"retries":{"bulk":0,"search":0},"throttled_millis":0,"requests_per_second":-1.0,"throttled_until_millis":0,"failures":[]}}%

The delete-by-query documentation for Tasks says the following:

If the request contains wait_for_completion=false then Elasticsearch will perform some preflight checks, launch the request, and then return a task which can be used with Tasks APIs to cancel or get the status of the task. Elasticsearch will also create a record of this task as a document at .tasks/task/${taskId}. This is yours to keep or remove as you see fit. When you are done with it, delete it so Elasticsearch can reclaim the space it uses.

Yet when I run the following:

curl -XDELETE "http:localhost/_tasks/x0i0D1FdEs-M29DDewnPwkg:257894116"

I get

No handler found for uri [/_tasks/x0i0D1FdEs-M29DDewnPwkg:257894116] and method [DELETE]%

答:
You need to delete the task with the following command</p>

```<code>curl -XDELETE "http:localhost/.tasks/task/x0i0D1FdEs-M29DDewnPwkg:257894116"
</code>```

Body:
You need to delete the task with the following command

curl -XDELETE "http:localhost/.tasks/task/x0i0D1FdEs-M29DDewnPwkg:257894116"


问:
get information from struct in swift file
so i have a class swift file that has a UserAccount class like this

```<code>class UserAccount{

 var userName: String!
 var email: String!
 var instaGram: String!
 var timeCreated: String!
 var like: String!
 var role: String!
 var active: String!
 var id: String!

init(userName: String, email: String, instaGram: String, timeCreated: String, like: String, role: String, active: String, id: String){

    self.userName = userName
    self.email = email
    self.instaGram  = instaGram
    self.timeCreated = timeCreated
    self.like = like
    self.role = role
    self.active = active
    self.id = id

 }
</code>```

}

i have login view controller where i get the class variables and do my json and assign their values like this :

```<code>var userAcount = [UserAccount]() // Array Of Object
var user = UserAccount(userName: "", email: "", instaGram: "", timeCreated: "", like: "", role: "", active: "", id: "") //Init of Object
</code>```

This is where i get my Json and add its value to its corresponding user class varible, i do this on my login view controller:

```<code>self.user.userName = userData.value(forKey: "userName") as! String
self.user.email = userData.value(forKey: "email") as! String
self.user.instaGram = userData.value(forKey: "instaGram") as! String
self.user.timeCreated = userData.value(forKey: "timeCreated") as! String
self.user.role = userData.value(forKey: "role") as! String
self.user.like = userData.value(forKey: "likes") as! String
self.user.id = userData.value(forKey: "id") as! String
self.user.active = userData.value(forKey: "active") as! String
</code>```

this is where i append the information to my class array:

```<code>self.userAcount.append(self.user)
</code>```

now my problem is that i dont know how to display the information in the UserAccount class on other view controllers, example the user profile view controller, is my first time working with users and profile, any help would be appreciated it, thank you

答:
In another ViewController make a Instance of your UserAccount.
When you wake that new view controller, pass value of UserAccount, to pass value you have two option
1. Storyborad/Segue

```<code>func prepare(for segue: UIStoryboardSegue, sender: Any?){
      if segue.identifier == "identifier"{
        let destinationVC = segue.destination as? YourViewController
        destinationVC.userAcount = self.userAcount
      }
   }
</code>```

2. By code

```<code>let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
   let controller = storyBoard.instantiateViewController(withIdentifier:      identifier)
   controller.user = self.user
</code>```

and now to access in your NewViewController you can simply access by

```<code>let userName = self.user.userName
</code>```

Body:
so i have a class swift file that has a UserAccount class like this

class UserAccount{

 var userName: String!
 var email: String!
 var instaGram: String!
 var timeCreated: String!
 var like: String!
 var role: String!
 var active: String!
 var id: String!

init(userName: String, email: String, instaGram: String, timeCreated: String, like: String, role: String, active: String, id: String){

    self.userName = userName
    self.email = email
    self.instaGram  = instaGram
    self.timeCreated = timeCreated
    self.like = like
    self.role = role
    self.active = active
    self.id = id

 }

}

i have login view controller where i get the class variables and do my json and assign their values like this :

var userAcount = [UserAccount]() // Array Of Object
var user = UserAccount(userName: "", email: "", instaGram: "", timeCreated: "", like: "", role: "", active: "", id: "") //Init of Object

This is where i get my Json and add its value to its corresponding user class varible, i do this on my login view controller:

self.user.userName = userData.value(forKey: "userName") as! String
self.user.email = userData.value(forKey: "email") as! String
self.user.instaGram = userData.value(forKey: "instaGram") as! String
self.user.timeCreated = userData.value(forKey: "timeCreated") as! String
self.user.role = userData.value(forKey: "role") as! String
self.user.like = userData.value(forKey: "likes") as! String
self.user.id = userData.value(forKey: "id") as! String
self.user.active = userData.value(forKey: "active") as! String

this is where i append the information to my class array:

self.userAcount.append(self.user)

now my problem is that i dont know how to display the information in the UserAccount class on other view controllers, example the user profile view controller, is my first time working with users and profile, any help would be appreciated it, thank you

Body:
In another ViewController make a Instance of your UserAccount.
When you wake that new view controller, pass value of UserAccount, to pass value you have two option
1. Storyborad/Segue

func prepare(for segue: UIStoryboardSegue, sender: Any?){
      if segue.identifier == "identifier"{
        let destinationVC = segue.destination as? YourViewController
        destinationVC.userAcount = self.userAcount
      }
   }

2. By code

let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
   let controller = storyBoard.instantiateViewController(withIdentifier:      identifier)
   controller.user = self.user

and now to access in your NewViewController you can simply access by

let userName = self.user.userName


问:
How to read test data from csv for JSON requests other than using set options
I used the set feature of Karate to change the values in keys using JSON expression.  I used it mainly to change the request contents based on test scenarios. This gave me the capability to avoid reading lot of test data from csv files. However, still in some situations, I prefer to use csv.

For example, I have around 230 test scenarios as post requests and I have 130 different customer information which I need to use on the 230 test cases based on the context. The customer information includes first, last names, age, address etc. However, the schema is same. If I need to use something like groovy template engines what will be the best approach to use in Karate

I need to keep these data in a csv, read it and pass the values to a JSON template before I fire the request. I need to still rely on csv/ external sources because these data becomes obsolete very often and I need to change it frequently. Could you please share your thoughts on this?

答:
I agree with your approach. I also think it’s better to read data from JSON array or using the table capability. I am working on that now. I work on a premise which has a lot of access restrictions. I inform the team about your answers. We keep a watch on these questions. However, I cannot login to stack overflow from office. So got delayed to respond on this. Sorry for the delay.

Now I am mainly doing an R&D to find a solution to test web services which can be integrated with the webdriver + DB validations. We earlier decided to go with rest assured. After using karate we have definitely changed our mind. One of our friend who work in ThoughtWorks suggested about karate and we came to know about it.

We are really impressed with its capability and also really happy to see the questions posted in stack overflow are so quickly answered. This gives us more confidence to use Karate. I would suggest that karate needs an individual website like rest assured.


问:
Show how counting semaphores can be implemented using only binary semaphores and ordinary machine instructions?
I am studying for a midterm and this was one of the practice questions: Show how counting semaphores (i.e, semaphores that can hold an arbitrary value) can be implemented using only binary semaphores and ordinary machine instructions?

I'm not even sure where so start. I found this online;

```<code>P(s) { Pb(mutex_s); s = s-1; if(s < 0) {Vb(mutex_s); Pb(delay_s);} Vb(mutex_s); }
V(s) { Pb(mutex_s); s = s+1; if(s <= 0) Vb(delay_s); else Vb(mutex_s); }
</code>```

Unfortunately, I don't really understand what the answer is telling me.  Can anyone explain this answer to me, or show me in pseudo code how to answer?

答:
I am having a similar question which I think would have the same answer, i.e., "How can you implement a counting semaphore using mutex".

Notice that binary semaphores can be thought of as mutexes. In fact, on systems that do not provide mutex locks, binary semaphores can be used instead for providing mutual exclusion.

```<code>Mutex counting_mutex;    // used for accessing the shared variable count
Integer count = n;       // number of resource instances
Mutex mutex;             // the counting semaphore as mutex/binary semaphore
List waiting_list = [];  // list of waiting processes

/* ... */

// Entry Section
acquire(counting_mutex);
count--;
release(counting_mutex);

if (count < 0)
    add this process to waiting_list and have it sleep()

acquire(mutex);
/* ... Critical Section ... */
release(mutex);

// Exit Section
acquire(counting_mutex);
count++;
release(counting_mutex);

if (count <= 0)
    pull a process from waiting_list and call wakeup()
</code>```

Body:
I am studying for a midterm and this was one of the practice questions: Show how counting semaphores (i.e, semaphores that can hold an arbitrary value) can be implemented using only binary semaphores and ordinary machine instructions?

I'm not even sure where so start. I found this online;

P(s) { Pb(mutex_s); s = s-1; if(s < 0) {Vb(mutex_s); Pb(delay_s);} Vb(mutex_s); }
V(s) { Pb(mutex_s); s = s+1; if(s <= 0) Vb(delay_s); else Vb(mutex_s); }

Unfortunately, I don't really understand what the answer is telling me.  Can anyone explain this answer to me, or show me in pseudo code how to answer?

Body:
I am having a similar question which I think would have the same answer, i.e., "How can you implement a counting semaphore using mutex".

Notice that binary semaphores can be thought of as mutexes. In fact, on systems that do not provide mutex locks, binary semaphores can be used instead for providing mutual exclusion.

Mutex counting_mutex;    // used for accessing the shared variable count
Integer count = n;       // number of resource instances
Mutex mutex;             // the counting semaphore as mutex/binary semaphore
List waiting_list = [];  // list of waiting processes

/* ... */

// Entry Section
acquire(counting_mutex);
count--;
release(counting_mutex);

if (count < 0)
    add this process to waiting_list and have it sleep()

acquire(mutex);
/* ... Critical Section ... */
release(mutex);

// Exit Section
acquire(counting_mutex);
count++;
release(counting_mutex);

if (count <= 0)
    pull a process from waiting_list and call wakeup()


问:
deallocating array of struct pointers in c implementation of priority queue
I have an issue freeing my array of struct pointers for a priority queue that I am implementing. I create two dynamic arrays of node pointers with a fixed size from client c program. The array heapMap contains node pointers that map to each created node with a specific ID integer value and the array heap is the heap array that contains the nodes with respect to their current values.

Everything seems to work, however, my pq_free function seems to cause errors or doesn't properly deallocate the arrays. Any help would be appreciated

Structures

```<code>typedef struct node_struct{
  int ID;
  double val;
}NODE;

struct pq_struct {
  char heapType;
  int max;
  int inUse;
  NODE ** heap;  //BOTH have a specific capacity
  NODE **heapMap; //array of pointers to each
};
</code>```

This is the function I use to allocate memory for the structure.

```<code>    PQ * pq_create(int capacity, int min_heap){

  PQ * newQueue = (PQ*) malloc(sizeof(PQ)); //Allocate memory for a new heap
  newQueue->max = capacity;
  newQueue->inUse = 0;
  int inUse = 1;//1 in use by default, the 0th point in the array is left alone intentionally

  //If min_heap == 0, it it is a max heap, any other value is a min heap.
  if(min_heap != 0){
    newQueue->heapType = 'm';
  }else{
    newQueue->heapType = 'M';
  }

  //Allocate memory for heapMap and heap..

  newQueue->heap = (NODE**) malloc(sizeof(NODE*)*capacity); //array of nodes, the heap

  newQueue->heapMap = (NODE**) malloc(sizeof(NODE*) * capacity);//array of node pointers, the HEAPMAP
  int i = 0;
  for (i = 0; i < capacity + 1;i++) {
      newQueue->heapMap[i] = NULL;
  }

  //return PQ pointer

  return newQueue;
}
</code>```

This is my pq_free function that doesn't seem to work properly. Thanks for help in advance.

```<code> void pq_free(PQ * pq){
 //free all nodes

 NODE * temp;
 NODE ** temp2;
 int i;
 for (i = 0; i < pq->inUse; i++) {
     if (pq->heapMap[i] != NULL) {
         temp = pq->heapMap[i];
         free(temp);

     }
 }
 //pq->heapMap = NULL;
 free(pq->heap);
 free(pq->heapMap);
 free(pq);

}
</code>```

答:
As I was once railed on this site for doing this, I feel obligated to do the same to you. You shouldn't cast malloc because it is automatically cast to the assigned data type and can lead to some bad situations.

Other than that how are the individual nodes allocated? What errors specifically are given? I think you are also walking off your heapMap as you allocate capacity but iterate over capacity + 1 elements.

Body:
I have an issue freeing my array of struct pointers for a priority queue that I am implementing. I create two dynamic arrays of node pointers with a fixed size from client c program. The array heapMap contains node pointers that map to each created node with a specific ID integer value and the array heap is the heap array that contains the nodes with respect to their current values.

Everything seems to work, however, my pq_free function seems to cause errors or doesn't properly deallocate the arrays. Any help would be appreciated

Structures

typedef struct node_struct{
  int ID;
  double val;
}NODE;

struct pq_struct {
  char heapType;
  int max;
  int inUse;
  NODE ** heap;  //BOTH have a specific capacity
  NODE **heapMap; //array of pointers to each
};

This is the function I use to allocate memory for the structure.

    PQ * pq_create(int capacity, int min_heap){

  PQ * newQueue = (PQ*) malloc(sizeof(PQ)); //Allocate memory for a new heap
  newQueue->max = capacity;
  newQueue->inUse = 0;
  int inUse = 1;//1 in use by default, the 0th point in the array is left alone intentionally

  //If min_heap == 0, it it is a max heap, any other value is a min heap.
  if(min_heap != 0){
    newQueue->heapType = 'm';
  }else{
    newQueue->heapType = 'M';
  }

  //Allocate memory for heapMap and heap..

  newQueue->heap = (NODE**) malloc(sizeof(NODE*)*capacity); //array of nodes, the heap

  newQueue->heapMap = (NODE**) malloc(sizeof(NODE*) * capacity);//array of node pointers, the HEAPMAP
  int i = 0;
  for (i = 0; i < capacity + 1;i++) {
      newQueue->heapMap[i] = NULL;
  }

  //return PQ pointer

  return newQueue;
}

This is my pq_free function that doesn't seem to work properly. Thanks for help in advance.

 void pq_free(PQ * pq){
 //free all nodes

 NODE * temp;
 NODE ** temp2;
 int i;
 for (i = 0; i < pq->inUse; i++) {
     if (pq->heapMap[i] != NULL) {
         temp = pq->heapMap[i];
         free(temp);

     }
 }
 //pq->heapMap = NULL;
 free(pq->heap);
 free(pq->heapMap);
 free(pq);

}


答:
If the object that is desired is declared in the global scope. The desired object will be accessible anytime a script tag is declared.

Example:

```<code><HTML>
<HEAD>
<SCRIPT>
    var test = {
      foo: 'bar'
    };

    var somethingIDontWant = 1;
    var iDontCareAboutYouEither = {
        blag: 1 + 1
    };
</SCRIPT>
</HEAD>
<BODY>
<DIV>UGLY HTML</DIV>
<SCRIPT>
//INSERT CUSTOM SCRIPT FOR ACCESSING DESIRED OBJECT//
console.log(test)
</SCRIPT>
</BODY>
</HTML>
</code>```

The console can still access var test..even in later defined script in the body...

Output:
{foo: 'bar'}

Title: How to extract variable from script tag in html blob

Body:
I am trying to figure out how to extract a variable from a giant string of html. A simplified example is below:

Update Here is a screen shot of trying to use the common approach called out below. Doing something as simple as test['foo'] doesn't work. This is a string returned from a server and is never loaded into the actual document or window. It's just an html object that's kept in memory.

https://jsfiddle.net/hvpvg3o4/

HTML

JavaScript

var testTag = document.getElementById('test');
var scriptTag = testTag.getElementsByTagName('script');
// var testObj = ?;

I was hoping that I could just get the text from the script tag and either run eval or some JSON.parse, but since there's other stuff within the script tag, I can't

Is there some way to extract a variable from a script tag or some fancy regex to do so?

Body:
If the object that is desired is declared in the global scope. The desired object will be accessible anytime a script tag is declared.

Example:

<HTML>
<HEAD>
<SCRIPT>
    var test = {
      foo: 'bar'
    };

    var somethingIDontWant = 1;
    var iDontCareAboutYouEither = {
        blag: 1 + 1
    };
</SCRIPT>
</HEAD>
<BODY>
<DIV>UGLY HTML</DIV>
<SCRIPT>
//INSERT CUSTOM SCRIPT FOR ACCESSING DESIRED OBJECT//
console.log(test)
</SCRIPT>
</BODY>
</HTML>

The console can still access var test..even in later defined script in the body...

Output:
{foo: 'bar'}


问:
Using self join/inner join to get the data by adding all the above rows data, in SQL Server
I am working with SQL server, the query details are as below:

Need to get the calculative column whose result will be the addition of all the above rows. And I can't use correlated queries, Lag and Lead as it is not supported.

I tried using self-join/inner join/left outer join, the only problem I am facing is due to group by clause of other columns the result is not coming as expected.

For example, data is like

Expected Output

But the output I am getting due to group by clause applied on Column4.
Output getting is like below

Is there some alternative of GROUP BY clause or other alternatives?

答:
It is resolved!!

Earlier my query was like,
SELECT a.*,
CASE WHEN col4!= A THEN SUM col3 ELSE 0 END
FROM a
GROUP BY col4, *...

This groupby was causing issue as it was giving the expected output

The things I changes in the query is,
SELECT a.*,
SUM(CASE WHEN col4!= A THEN col3 ELSE 0 END)
FROM a
GROUP BY (CASE WHEN col4!= A THEN col3 ELSE 0 END)

Now it is giving result as expected.

Thank you everyone for the help!!


问:
Library for displaying image sets on an iPad
I'm looking for some cool libraries out there to display a bunch of images in my iPad application.

I think they are already out there, and I don't have to start from scratch, but I can't find some good ones.

答:
Check out KTPhotoBrowser, I use it in a universal app, and it works pretty good.

Also, search Github : Photo Gallery for more open-source solutions.


问:
Editing WooCommerce coupon message
How do I correct/edit the alignment/contents of the coupon message (refer to the screenshot) that pops up when a user enters the coupon code at the cart checkout page in WordPress?

答:
You need to find the template inside the woocommerce plugin's template folder.

Then create a woocommerce folder in your child theme, and copy the template there (same folder strucure).

Finally you make changes to your child theme's coupon template.

Read the comments for this file

ContentLicense: CC BY-SA 4.0

Title: Editing WooCommerce coupon message