问:
Why do Sublime Text 3 Themes not affect the sidebar?
I generally only use dark themes for coding, so it's really annoying that Sublime Text 3's sidebar stays light themed whatever theme you apply.

Does anyone know how to change this?

My configuration: Mac OSX 10.10.1 Yosemite, Sublime Text 3 Stable Channel, Build 3065

答:
Here's the short version:

.sublime-theme files change the look of the UI including the Sidebar and File Tabs.

Defining these are a tremendous pain, so save yourself a lot of time and install the Theme Menu Switcher package.

Update: Sublime Text 3 has fundamentally changed the way Color Schemes and Themes work, and has broken many of the packages that were built to handle them. I can no longer confirm the accuracy of this post, nor the functionality of the packages mentioned herein because the Sublime developers have not fully explained the changes to the customization system nor addressed how to fix them. And, at the very best, they are far more difficult to change.

At this point, this post should only be used as a reference to the differences between "themes" and "color schemes" in Sublime Text 2, as I myself have yet to successfully change a theme nor color scheme in Sublime Text 3.

I will update this post as I can dedicate more time to unraveling this Sublime Customization Quagmire.

Here's the long version:

Figure 1: The difference between "Color Schemes" and "Themes" - In the Sublime Community these terms are often confused and used interchangeably.

Changing the look of Sublime is a relatively difficult endeavor, for three main reasons:

Poorly chosen terminology

Misinformation in the Sublime Community

Installation Nightmare

Terminology

There are 2 different sections of Sublime that can be customized:

the editable region (the purple regions)

the User Interface (the green regions)

These use two different file types, and they do not accurately reflect the terminology.

The "Why?" of this decision is compatibility, and for brevity's sake I won't get into it here, but the fallout of this effort is:

The file type called tmTheme does not affect the theme, it affects the Color Scheme.

Color Schemes (highlighted in purple)

affect the look of the editable region (more specifically, the editable characters, ie what color they are when highlighted or not highlighted, etc).

relatively easy to produce

Color Schemes are Mistakenly called "Themes" all over the Sublime Community.

Themes (highlighted in green)

.sublime-theme files change the Theme, or the UI aspects of Sublime.

difficult to produce

It is difficult to find true Sublime Themes, compared to "Color Schemes"

Misinformation

Many packages claim to change the Theme, but actually change the Color Scheme. This is usually because the people producing them don't know that "Theme" specifically refers to the UI.

So another level of difficulty is finding a true "Theme" package, rather than Color Scheme.

Even some legit websites do not correctly make a distinction between the two, which adds to the challenges. For instance, colorsublime.com has a tutorial on changing the sublime "theme", but actually references the "Color Scheme" file type (.tmTheme).

Installation Pains

Themes and Color Schemes are hard to install and define. In fact, it's shocking how difficult the process is. The difficulty is further exacerbated with a fundamental change in installation and definition requirements in Sublime Text 3 that are not fully explained, which breaks many of the packages we once were reliant upon to change the Themes and Color Schemes.

It requires installing an actual Theme package (good luck finding one by browsing Packages in Package Control), defining it in settings, and then restarting Sublime. And, if you did something wrong, Sublime will simply replace your user-defined theme setting with the default. Yes, you heard me right, without notice or error message, Sublime will overwrite your theme definition.

But with Themes Menu Switcher All you need to do is go to Preferences > Theme and you'll see a list of all themes you have installed. You can also easily switch between themes without restarting Sublime.

Here's a sample from the website:

I have no affiliation with Theme Menu Switcher at all, I'm just a fan.

Again, Theme Menu Switcher does not work the same in Sublime Text 3. If you need to have a customized look, I recommend not to update to Sublime Text 3.


来源: stackexchange

问:
Changing Schema Name
I have created a table in a  schema called sample1 and now i want to change the schema name of the table. I tried doing it by

alter schema sample2 transfer sample1.table1

But it gives me an error.

How do I change the schema name from sample1 to sample2

答:
Did you try this:

```<code>sp_changeobjectowner '[sample1].[transfer]', 'sample2'
go
</code>```

I'm basing this on the comment you made to the other answer that you already had sample2 created.

ContentLicense: CC BY-SA 2.5

Title: Changing Schema Name

Body:
Did you try this:

sp_changeobjectowner '[sample1].[transfer]', 'sample2'
go

I'm basing this on the comment you made to the other answer that you already had sample2 created.


问:
where does Jetty save files on upload temporarily?
I have a very basic question about file upload with embedded Jetty.

When I upload a large file, I know that Jetty server buffers it somewhere. Where does this buffer exist?

Also, Is there a way to disable the buffer and stream the request data directly to a destination such as HDFS?

If we can't disable this buffering, at least I need to have a control on deleting the tmp file after the file upload is complete.

Thanks in advance for the help.

答: That's defined by the servlet spec location value found in the MultipartConfigElement, typically declared as an @MultipartConfig annotation on the servlet you have receiving the uploaded files.

ContentLicense: CC BY-SA 3.0


问:
How can I schedule a job to run a SQL query daily?
I need to know how to make a SQL query run daily using a SQL Server Agent job, with minimum required configuration settings.</p>

答:
To do this in t-sql, you can use the following system stored procedures to schedule a daily job. This example schedules daily at 1:00 AM. See Microsoft help for details on syntax of the individual stored procedures and valid range of parameters.</p>

```<code>DECLARE @job_name NVARCHAR(128), @description NVARCHAR(512), @owner_login_name NVARCHAR(128), @database_name NVARCHAR(128);

SET @job_name = N'Some Title';
SET @description = N'Periodically do something';
SET @owner_login_name = N'login';
SET @database_name = N'Database_Name';

-- Delete job if it already exists:
IF EXISTS(SELECT job_id FROM msdb.dbo.sysjobs WHERE (name = @job_name))
BEGIN
    EXEC msdb.dbo.sp_delete_job
        @job_name = @job_name;
END

-- Create the job:
EXEC  msdb.dbo.sp_add_job
    @job_name=@job_name,
    @enabled=1,
    @notify_level_eventlog=0,
    @notify_level_email=2,
    @notify_level_netsend=2,
    @notify_level_page=2,
    @delete_level=0,
    @description=@description,
    @category_name=N'[Uncategorized (Local)]',
    @owner_login_name=@owner_login_name;

-- Add server:
EXEC msdb.dbo.sp_add_jobserver @job_name=@job_name;

-- Add step to execute SQL:
EXEC msdb.dbo.sp_add_jobstep
    @job_name=@job_name,
    @step_name=N'Execute SQL',
    @step_id=1,
    @cmdexec_success_code=0,
    @on_success_action=1,
    @on_fail_action=2,
    @retry_attempts=0,
    @retry_interval=0,
    @os_run_priority=0,
    @subsystem=N'TSQL',
    @command=N'EXEC my_stored_procedure; -- OR ANY SQL STATEMENT',
    @database_name=@database_name,
    @flags=0;

-- Update job to set start step:
EXEC msdb.dbo.sp_update_job
    @job_name=@job_name,
    @enabled=1,
    @start_step_id=1,
    @notify_level_eventlog=0,
    @notify_level_email=2,
    @notify_level_netsend=2,
    @notify_level_page=2,
    @delete_level=0,
    @description=@description,
    @category_name=N'[Uncategorized (Local)]',
    @owner_login_name=@owner_login_name,
    @notify_email_operator_name=N'',
    @notify_netsend_operator_name=N'',
    @notify_page_operator_name=N'';

-- Schedule job:
EXEC msdb.dbo.sp_add_jobschedule
    @job_name=@job_name,
    @name=N'Daily',
    @enabled=1,
    @freq_type=4,
    @freq_interval=1,
    @freq_subday_type=1,
    @freq_subday_interval=0,
    @freq_relative_interval=0,
    @freq_recurrence_factor=1,
    @active_start_date=20170101, --YYYYMMDD
    @active_end_date=99991231, --YYYYMMDD (this represents no end date)
    @active_start_time=010000, --HHMMSS
    @active_end_time=235959; --HHMMSS
</code>```

ContentLicense: CC BY-SA 4.0

Body:
To do this in t-sql, you can use the following system stored procedures to schedule a daily job. This example schedules daily at 1:00 AM. See Microsoft help for details on syntax of the individual stored procedures and valid range of parameters.

DECLARE @job_name NVARCHAR(128), @description NVARCHAR(512), @owner_login_name NVARCHAR(128), @database_name NVARCHAR(128);

SET @job_name = N'Some Title';
SET @description = N'Periodically do something';
SET @owner_login_name = N'login';
SET @database_name = N'Database_Name';

-- Delete job if it already exists:
IF EXISTS(SELECT job_id FROM msdb.dbo.sysjobs WHERE (name = @job_name))
BEGIN
    EXEC msdb.dbo.sp_delete_job
        @job_name = @job_name;
END

-- Create the job:
EXEC  msdb.dbo.sp_add_job
    @job_name=@job_name,
    @enabled=1,
    @notify_level_eventlog=0,
    @notify_level_email=2,
    @notify_level_netsend=2,
    @notify_level_page=2,
    @delete_level=0,
    @description=@description,
    @category_name=N'[Uncategorized (Local)]',
    @owner_login_name=@owner_login_name;

-- Add server:
EXEC msdb.dbo.sp_add_jobserver @job_name=@job_name;

-- Add step to execute SQL:
EXEC msdb.dbo.sp_add_jobstep
    @job_name=@job_name,
    @step_name=N'Execute SQL',
    @step_id=1,
    @cmdexec_success_code=0,
    @on_success_action=1,
    @on_fail_action=2,
    @retry_attempts=0,
    @retry_interval=0,
    @os_run_priority=0,
    @subsystem=N'TSQL',
    @command=N'EXEC my_stored_procedure; -- OR ANY SQL STATEMENT',
    @database_name=@database_name,
    @flags=0;

-- Update job to set start step:
EXEC msdb.dbo.sp_update_job
    @job_name=@job_name,
    @enabled=1,
    @start_step_id=1,
    @notify_level_eventlog=0,
    @notify_level_email=2,
    @notify_level_netsend=2,
    @notify_level_page=2,
    @delete_level=0,
    @description=@description,
    @category_name=N'[Uncategorized (Local)]',
    @owner_login_name=@owner_login_name,
    @notify_email_operator_name=N'',
    @notify_netsend_operator_name=N'',
    @notify_page_operator_name=N'';

-- Schedule job:
EXEC msdb.dbo.sp_add_jobschedule
    @job_name=@job_name,
    @name=N'Daily',
    @enabled=1,
    @freq_type=4,
    @freq_interval=1,
    @freq_subday_type=1,
    @freq_subday_interval=0,
    @freq_relative_interval=0,
    @freq_recurrence_factor=1,
    @active_start_date=20170101, --YYYYMMDD
    @active_end_date=99991231, --YYYYMMDD (this represents no end date)
    @active_start_time=010000, --HHMMSS
    @active_end_time=235959; --HHMMSS


问:
JSON Get List of attributes values
I have the following JSON, and I want to take a list of IDs with its values

For example in LINQ something like this: result.Select(x=>x.id)

I tried this:

```<code> var inner = outer["pictures"].Value<JArray>().ToList();
</code>```

I have a list there but with all attributes but I am not able to select just IDs since it is an anonymous list.

```<code>    outer
{{
  "id": "669654603",
  "pictures": [
    {
      "id": "659745-MLA25600661898_052017",
      "url": "http://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "size": "500x365",
      "max_size": "625x457",
      "quality": ""
    },
    {
      "id": "908422-MLA25658267858_062017",
      "url": "http://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "size": "47x47",
      "max_size": "47x47",
      "quality": ""
    },
    {
      "id": "794138-MLA25658267889_062017",
      "url": "http://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "size": "40x40",
      "max_size": "40x40",
      "quality": ""
    }
  ]

}}
</code>```

答:
When working with Newtonsoft JSON you can do it like this:</p>

```<code>var values = JObject.Parse(jsonString)["pictures"].Select(p => p["id"].Value<string>()).ToList();
</code>```

Title: JSON Get List of attributes values

Body:
I have the following JSON, and I want to take a list of IDs with its values

For example in LINQ something like this: result.Select(x=>x.id)

I tried this:

 var inner = outer["pictures"].Value<JArray>().ToList();

I have a list there but with all attributes but I am not able to select just IDs since it is an anonymous list.

    outer
{{
  "id": "669654603",
  "pictures": [
    {
      "id": "659745-MLA25600661898_052017",
      "url": "http://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "size": "500x365",
      "max_size": "625x457",
      "quality": ""
    },
    {
      "id": "908422-MLA25658267858_062017",
      "url": "http://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "size": "47x47",
      "max_size": "47x47",
      "quality": ""
    },
    {
      "id": "794138-MLA25658267889_062017",
      "url": "http://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "size": "40x40",
      "max_size": "40x40",
      "quality": ""
    }
  ]

}}

Body:
When working with Newtonsoft JSON you can do it like this:

var values = JObject.Parse(jsonString)["pictures"].Select(p => p["id"].Value<string>()).ToList();


问:
Numpy ‘smart’ symmetric matrix
Is there a smart and space-efficient symmetric matrix in numpy which automatically (and transparently) fills the position at [j][i] when [i][j] is written to?

```<code>import numpy
a = numpy.symmetric((3, 3))
a[0][1] = 1
a[1][0] == a[0][1]
# True
print(a)
# [[0 1 0], [1 0 0], [0 0 0]]

assert numpy.all(a == a.T) # for any symmetric matrix
</code>```

An automatic Hermitian would also be nice, although I won’t need that at the time of writing.

答:
It is trivial to Pythonically fill in [i][j] if [j][i] is filled in.  The storage question is a little more interesting. One can augment the numpy array class with a packed attribute that is useful both to save storage and to later read the data.

```<code>class Sym(np.ndarray):

    # wrapper class for numpy array for symmetric matrices. New attribute can pack matrix to optimize storage.
    # Usage:
    # If you have a symmetric matrix A as a shape (n,n) numpy ndarray, Sym(A).packed is a shape (n(n+1)/2,) numpy array
    # that is a packed version of A.  To convert it back, just wrap the flat list in Sym().  Note that Sym(Sym(A).packed)

    def __new__(cls, input_array):
        obj = np.asarray(input_array).view(cls)

        if len(obj.shape) == 1:
            l = obj.copy()
            p = obj.copy()
            m = int((np.sqrt(8 * len(obj) + 1) - 1) / 2)
            sqrt_m = np.sqrt(m)

            if np.isclose(sqrt_m, np.round(sqrt_m)):
                A = np.zeros((m, m))
                for i in range(m):
                    A[i, i:] = l[:(m-i)]
                    A[i:, i] = l[:(m-i)]
                    l = l[(m-i):]
                obj = np.asarray(A).view(cls)
                obj.packed = p

            else:
                raise ValueError('One dimensional input length must be a triangular number.')

        elif len(obj.shape) == 2:
            if obj.shape[0] != obj.shape[1]:
                raise ValueError('Two dimensional input must be a square matrix.')
            packed_out = []
            for i in range(obj.shape[0]):
                packed_out.append(obj[i, i:])
            obj.packed = np.concatenate(packed_out)

        else:
            raise ValueError('Input array must be 1 or 2 dimensional.')

        return obj

    def __array_finalize__(self, obj):
        if obj is None: return
        self.packed = getattr(obj, 'packed', None)
</code>```

```

Title: Numpy ‘smart’ symmetric matrix

Body:
Is there a smart and space-efficient symmetric matrix in numpy which automatically (and transparently) fills the position at [j][i] when [i][j] is written to?

import numpy
a = numpy.symmetric((3, 3))
a[0][1] = 1
a[1][0] == a[0][1]
# True
print(a)
# [[0 1 0], [1 0 0], [0 0 0]]

assert numpy.all(a == a.T) # for any symmetric matrix

An automatic Hermitian would also be nice, although I won’t need that at the time of writing.

Body:
It is trivial to Pythonically fill in [i][j] if [j][i] is filled in.  The storage question is a little more interesting. One can augment the numpy array class with a packed attribute that is useful both to save storage and to later read the data.

class Sym(np.ndarray):

    # wrapper class for numpy array for symmetric matrices. New attribute can pack matrix to optimize storage.
    # Usage:
    # If you have a symmetric matrix A as a shape (n,n) numpy ndarray, Sym(A).packed is a shape (n(n+1)/2,) numpy array
    # that is a packed version of A.  To convert it back, just wrap the flat list in Sym().  Note that Sym(Sym(A).packed)

    def __new__(cls, input_array):
        obj = np.asarray(input_array).view(cls)

        if len(obj.shape) == 1:
            l = obj.copy()
            p = obj.copy()
            m = int((np.sqrt(8 * len(obj) + 1) - 1) / 2)
            sqrt_m = np.sqrt(m)

            if np.isclose(sqrt_m, np.round(sqrt_m)):
                A = np.zeros((m, m))
                for i in range(m):
                    A[i, i:] = l[:(m-i)]
                    A[i:, i] = l[:(m-i)]
                    l = l[(m-i):]
                obj = np.asarray(A).view(cls)
                obj.packed = p

            else:
                raise ValueError('One dimensional input length must be a triangular number.')

        elif len(obj.shape) == 2:
            if obj.shape[0] != obj.shape[1]:
                raise ValueError('Two dimensional input must be a square matrix.')
            packed_out = []
            for i in range(obj.shape[0]):
                packed_out.append(obj[i, i:])
            obj.packed = np.concatenate(packed_out)

        else:
            raise ValueError('Input array must be 1 or 2 dimensional.')

        return obj

    def __array_finalize__(self, obj):
        if obj is None: return
        self.packed = getattr(obj, 'packed', None)

```


问:
Change selected value if radio button is selected
I have a radio button:

```<code><input type="radio" name="editList" id="suc" value="S">Suc
</code>```

If I select radio button I disable lst2 as:

```<code> $('input:radio[name="editList"]')
                       .click(function () {
                           if ($(this).val() === "S") {
                               $('#lst2').prop('disabled', true);
                           } else {
                                $('#lst2').prop('disabled', false);
                           }
                       });
</code>```

But now I want know how can I change value of lst2 automatically with the same value of lst1 if radio button is selected, how can I do it into onChange state?

Select JS:

```<code>function getlst2(sender) {

  // sender: jQuery Object which called this method.
  sender.addClass("changed");
  $("#lst2").getJSONCatalog({
    url: 'https://demo9451608.mockable.io/getTest',
    valueProperty: "id",
    textProperty: "text"
  });
}

$("#lst1").getJSONCatalog({
  url: 'https://demo9451608.mockable.io/getTest',
  valueProperty: "key",
  textProperty: "value",
  onChange: getlst2
});
</code>```

Note: if radio is not selected you can choose lst2 value.

Demo

答:
You can use a checkbox "if in future the value need to be changed". A pure javascript solution as follows.

```<code>function handleClick(cb) {
if(cb.checked){
 document.getElementById('secondOption').disabled = true;
}
 else {
 document.getElementById('secondOption').disabled = false;
 document.getElementById('secondOption').value = "default";
}
}

 function check() {
   var checkBox = document.getElementById('secondOption').disabled;
   var selectedValue = document.getElementById('firstOption').value;
   var element = document.getElementById('secondOption');
       if(checkBox) {
element.value = selectedValue;
 }
}
</code>```

A working plunker Demo

Body:
I have a radio button:

<input type="radio" name="editList" id="suc" value="S">Suc

If I select radio button I disable lst2 as:

 $('input:radio[name="editList"]')
                       .click(function () {
                           if ($(this).val() === "S") {
                               $('#lst2').prop('disabled', true);
                           } else {
                                $('#lst2').prop('disabled', false);
                           }
                       });

But now I want know how can I change value of lst2 automatically with the same value of lst1 if radio button is selected, how can I do it into onChange state?

Select JS:

function getlst2(sender) {

  // sender: jQuery Object which called this method.
  sender.addClass("changed");
  $("#lst2").getJSONCatalog({
    url: 'https://demo9451608.mockable.io/getTest',
    valueProperty: "id",
    textProperty: "text"
  });
}

$("#lst1").getJSONCatalog({
  url: 'https://demo9451608.mockable.io/getTest',
  valueProperty: "key",
  textProperty: "value",
  onChange: getlst2
});

Note: if radio is not selected you can choose lst2 value.

Demo

Body:
You can use a checkbox "if in future the value need to be changed". A pure javascript solution as follows.

function handleClick(cb) {
if(cb.checked){
 document.getElementById('secondOption').disabled = true;
}
 else {
 document.getElementById('secondOption').disabled = false;
 document.getElementById('secondOption').value = "default";
}
}

 function check() {
   var checkBox = document.getElementById('secondOption').disabled;
   var selectedValue = document.getElementById('firstOption').value;
   var element = document.getElementById('secondOption');
       if(checkBox) {
element.value = selectedValue;
 }
}

A working plunker Demo


问:
Parsing json and searching through it
I have this code

```<code>import json
from pprint import pprint
json_data=open('bookmarks.json')
jdata = json.load(json_data)
pprint (jdata)
json_data.close()
</code>```

How can I search through it for u'uri': u'http:?

答:
Functions to search through and print dicts, like JSON.
*made in python 3

Search:

```<code>def pretty_search(dict_or_list, key_to_search, search_for_first_only=False):
    """
    Give it a dict or a list of dicts and a dict key (to get values of),
    it will search through it and all containing dicts and arrays
    for all values of dict key you gave, and will return you set of them
    unless you wont specify search_for_first_only=True

    :param dict_or_list:
    :param key_to_search:
    :param search_for_first_only:
    :return:
    """
    search_result = set()
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if key == key_to_search:
                if search_for_first_only:
                    return key_value
                else:
                    search_result.add(key_value)
            if isinstance(key_value, dict) or isinstance(key_value, list) or isinstance(key_value, set):
                _search_result = pretty_search(key_value, key_to_search, search_for_first_only)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
                        search_result.add(result)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, list) or isinstance(element, set) or isinstance(element, dict):
                _search_result = pretty_search(element, key_to_search, search_result)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
                        search_result.add(result)
    return search_result if search_result else None
</code>```

Print:

```<code>def pretty_print(dict_or_list, print_spaces=0):
    """
    Give it a dict key (to get values of),
    it will return you a pretty for print version
    of a dict or a list of dicts you gave.

    :param dict_or_list:
    :param print_spaces:
    :return:
    """
    pretty_text = ""
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if isinstance(key_value, dict):
                key_value = pretty_print(key_value, print_spaces + 1)
                pretty_text += "\t" * print_spaces + "{}:\n{}\n".format(key, key_value)
            elif isinstance(key_value, list) or isinstance(key_value, set):
                pretty_text += "\t" * print_spaces + "{}:\n".format(key)
                for element in key_value:
                    if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                        pretty_text += pretty_print(element, print_spaces + 1)
                    else:
                        pretty_text += "\t" * (print_spaces + 1) + "{}\n".format(element)
            else:
                pretty_text += "\t" * print_spaces + "{}: {}\n".format(key, key_value)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                pretty_text += pretty_print(element, print_spaces + 1)
            else:
                pretty_text += "\t" * print_spaces + "{}\n".format(element)
    else:
        pretty_text += str(dict_or_list)
    if print_spaces == 0:
        print(pretty_text)
    return pretty_text
</code>```

Title: Parsing json and searching through it

Body:
I have this code

import json
from pprint import pprint
json_data=open('bookmarks.json')
jdata = json.load(json_data)
pprint (jdata)
json_data.close()

How can I search through it for u'uri': u'http:?

Body:
Functions to search through and print dicts, like JSON.
*made in python 3

Search:

def pretty_search(dict_or_list, key_to_search, search_for_first_only=False):
    """
    Give it a dict or a list of dicts and a dict key (to get values of),
    it will search through it and all containing dicts and arrays
    for all values of dict key you gave, and will return you set of them
    unless you wont specify search_for_first_only=True

    :param dict_or_list:
    :param key_to_search:
    :param search_for_first_only:
    :return:
    """
    search_result = set()
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if key == key_to_search:
                if search_for_first_only:
                    return key_value
                else:
                    search_result.add(key_value)
            if isinstance(key_value, dict) or isinstance(key_value, list) or isinstance(key_value, set):
                _search_result = pretty_search(key_value, key_to_search, search_for_first_only)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
                        search_result.add(result)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, list) or isinstance(element, set) or isinstance(element, dict):
                _search_result = pretty_search(element, key_to_search, search_result)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
                        search_result.add(result)
    return search_result if search_result else None

Print:

def pretty_print(dict_or_list, print_spaces=0):
    """
    Give it a dict key (to get values of),
    it will return you a pretty for print version
    of a dict or a list of dicts you gave.

    :param dict_or_list:
    :param print_spaces:
    :return:
    """
    pretty_text = ""
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if isinstance(key_value, dict):
                key_value = pretty_print(key_value, print_spaces + 1)
                pretty_text += "\t" * print_spaces + "{}:\n{}\n".format(key, key_value)
            elif isinstance(key_value, list) or isinstance(key_value, set):
                pretty_text += "\t" * print_spaces + "{}:\n".format(key)
                for element in key_value:
                    if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                        pretty_text += pretty_print(element, print_spaces + 1)
                    else:
                        pretty_text += "\t" * (print_spaces + 1) + "{}\n".format(element)
            else:
                pretty_text += "\t" * print_spaces + "{}: {}\n".format(key, key_value)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                pretty_text += pretty_print(element, print_spaces + 1)
            else:
                pretty_text += "\t" * print_spaces + "{}\n".format(element)
    else:
        pretty_text += str(dict_or_list)
    if print_spaces == 0:
        print(pretty_text)
    return pretty_text


问:
Are GAN's unsupervised or supervised?
I hear from some sources that Generative adversarial networks are unsupervised ML, but i dont get it. Are Generative adversarial networks not in fact supervised?

1) 2-class case Real-against-Fake

Indeed one has to supply training data to the discriminator and this has to be "real" data, meaning data which i would label with f.e. 1. Even though one doesnt label the data explicit, one does so implicitly by presenting the discriminator in the first steps with training data, which you tell the discriminator is authentic. In that way you somehow tell the discriminator a labeling of the training data. And on the contrary a labeling of the noise data that is generated at the first steps of the generator, which the generator knows to be unauthentic.

2) Multi-class case

But it gets really strange in the multi class case. One has to supply descriptions in the training data. The obvious contradiction is that one supplies a response to an unsupervised ML algorithm.

答:
GANs are unsupervised learning algorithms that use a supervised loss as part of the training. The later appears to be where you are getting hung-up.

When we talk about supervised learning, we are usually talking about learning to predict a label associated with the data. The goal is for the model to generalize to new data.

In the GAN case, you don't have either of these components. The data comes in with no labels, and we are not trying to generalize any kind of prediction to new data. The goal is for the GAN to model what the data looks like (i.e., density estimation), and be able to generate new examples of what it has learned.

The GAN sets up a supervised learning problem in order to do unsupervised learning, generates fake / random looking data, and tries to determine if a sample is generated fake data or real data. This is a supervised component, yes. But it is not the goal of the GAN, and the labels are trivial.

The idea of using a supervised component for an unsupervised task is not particularly new. Random Forests have done this for a long time for outlier detection (also trained on random data vs real data), and the One-Class SVM  for outlier detection is technically trained in supervised fashion with the original data being the real class and a single point at the origin of the space (i.e., the zero vector) treated as the outlier class.

Title: Are GAN's unsupervised or supervised?


问:
Retrieve contents of a ZIP file on SharePoint without downloading it
I have written a bit of automated code that checks a SharePoint site and looks for a ZIP file (lets call it doc.zip).  If doc.zip is found, it downloads it, and then checks for a file (say target.docx).  doc.zip is about 300MB, and so I want to only download where necessary.

What I would like to know is that given SharePoint has some ZIP search capability, is it possible to write code using CSOM (c#) to find doc.zip, and then run some code to retrieve the contents of doc.zip without downloading it.

Just to re-iterate, I am comfortable with searching for files in a folder on SP, downloading the file, and unpacking zip entries.  What I need is to retrieve a ZIP files content on SP without downloading it.

E.g. is there a SP command:

```<code>cxt.Load(SomeZipFileQuery);
cxt.ExecuteQuery();
</code>```

Thanks in advance.

答:
Ok, I have proven yet again that stubbornness will prevail.

I have figured out that if I use the /_api/search?query='myfile.zip' web REST API to search for my file, this search will also match ZIP files that contain the file I need.  And it works perfectly.

Of course there is added (pain) of parsing an XML response, but it works very nicely for my code example.

At least if someone is looking for this solution here it is.  I wont bore anyone with code, as the /_api/search has probably been done to death already on other threads.

Body:
I have written a bit of automated code that checks a SharePoint site and looks for a ZIP file (lets call it doc.zip).  If doc.zip is found, it downloads it, and then checks for a file (say target.docx).  doc.zip is about 300MB, and so I want to only download where necessary.

What I would like to know is that given SharePoint has some ZIP search capability, is it possible to write code using CSOM (c#) to find doc.zip, and then run some code to retrieve the contents of doc.zip without downloading it.

Just to re-iterate, I am comfortable with searching for files in a folder on SP, downloading the file, and unpacking zip entries.  What I need is to retrieve a ZIP files content on SP without downloading it.

E.g. is there a SP command:

cxt.Load(SomeZipFileQuery);
cxt.ExecuteQuery();

Thanks in advance.


问:
Raw LWIP Send TCP Transmission to Static IP
I've got the TCP Echo example working well on my hardware, and yesterday figured out how to get a UDP Broadcast working. After further thought, I've realized is that what I really need is to be able to set up a TCP Connection to a Static IP, the idea being that my hardware can connect to a server of some sort and then use that connection for all its transactions. The difference is that whereas the echo example sets up a passive connection, that binds with the incoming source (as I understand it), I want to initiate the connection deliberately to a known IP.

Based on what I found on Wikia Here Here

I've attempted as a base case to implement a function that can send a packet to a Defined IP. I'm simply trying to send a packet to my PC, and I'm looking for it on Wireshark.

```<code>void echo_tx_tcp()
{
  err_t wr_err = ERR_OK;
  struct tcp_pcb *l_tcp_pcb;
  l_tcp_pcb = tcp_new();
  ip_addr_t dest_ip =
  { ((u32_t)0x0C0C0C2BUL) };
  wr_err = tcp_bind(l_tcp_pcb, &dest_ip, 12);
  wr_err = tcp_connect(l_tcp_pcb, &dest_ip, 12, echo_accept);
  tcp_sent(l_tcp_pcb, echo_sent);

  struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, 1024, PBUF_RAM);
  unsigned char buffer_send[1024] = "My Name Is TCP";
  p->payload = buffer_send;
  p->len = 1024;
  p->tot_len = 1024;

  wr_err = tcp_write(l_tcp_pcb, p->payload, p->len, 1);
  wr_err = tcp_output(l_tcp_pcb);

  if(wr_err == ERR_OK)
  {
    p->len++;
  }
  return;
}
</code>```

The last if statement just exists so that I can inspect the wr_err value with a debugger. The err is coming  back OK but the packet is not seen on wireshark. My setup is my hardare as well as my PC connected to a router in an isolated manner. The IP Address of the PC locally is 12.12.12.43

Am I missing a step here?

答:
The tcp_write() function will fail and return ERR_MEM if:

The length of the data exceeds the current send buffer size.

The length of the queue of the outgoing segment is larger than the upper limit defined in lwipopts.h.

The number of bytes available in the output queue can be retrieved with the tcp_sndbuf() function.

Potential solution(s):

Try again but send less data.

Monitor the amount of space available in the send buffer and only send (more) data when there is space available in the send buffer.

Suggestions:

tcp_snd_buf() can be used to find out how much send buffer space is available.

tcp_sent() can be implemented with callback function, that will be called when send butter space is available.

Body:
I've got the TCP Echo example working well on my hardware, and yesterday figured out how to get a UDP Broadcast working. After further thought, I've realized is that what I really need is to be able to set up a TCP Connection to a Static IP, the idea being that my hardware can connect to a server of some sort and then use that connection for all its transactions. The difference is that whereas the echo example sets up a passive connection, that binds with the incoming source (as I understand it), I want to initiate the connection deliberately to a known IP.

Based on what I found on Wikia Here Here

I've attempted as a base case to implement a function that can send a packet to a Defined IP. I'm simply trying to send a packet to my PC, and I'm looking for it on Wireshark.

void echo_tx_tcp()
{
  err_t wr_err = ERR_OK;
  struct tcp_pcb *l_tcp_pcb;
  l_tcp_pcb = tcp_new();
  ip_addr_t dest_ip =
  { ((u32_t)0x0C0C0C2BUL) };
  wr_err = tcp_bind(l_tcp_pcb, &dest_ip, 12);
  wr_err = tcp_connect(l_tcp_pcb, &dest_ip, 12, echo_accept);
  tcp_sent(l_tcp_pcb, echo_sent);

  struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, 1024, PBUF_RAM);
  unsigned char buffer_send[1024] = "My Name Is TCP";
  p->payload = buffer_send;
  p->len = 1024;
  p->tot_len = 1024;

  wr_err = tcp_write(l_tcp_pcb, p->payload, p->len, 1);
  wr_err = tcp_output(l_tcp_pcb);

  if(wr_err == ERR_OK)
  {
    p->len++;
  }
  return;
}

The last if statement just exists so that I can inspect the wr_err value with a debugger. The err is coming  back OK but the packet is not seen on wireshark. My setup is my hardare as well as my PC connected to a router in an isolated manner. The IP Address of the PC locally is 12.12.12.43

Am I missing a step here?


问:
ng-jhipster development creates compilation errors
I face the following problem. I cannot test the ng-jhipster module.
Steps followed:
ng-jhipster:
- yarn link
- yarn install ( all the steps have been executed correctly)

My project:
- yarn link ng-jhipster
- yarn start

ERROR in [at-loader] ./src/main/webapp/app/blocks/interceptor/errorhandler.interceptor.ts:5:14
    TS2415: Class 'ErrorHandlerInterceptor' incorrectly extends base class 'HttpInterceptor'.
  Types of property 'requestIntercept' are incompatible.
    Type '(options?: RequestOptionsArgs) => RequestOptionsArgs' is not assignable to type '(options?: RequestOpt
ionsArgs) => RequestOptionsArgs'. Two different types with this name exist, but they are unrelated.
      Types of parameters 'options' and 'options' are incompatible.
        Type 'RequestOptionsArgs' is not assignable to type 'RequestOptionsArgs'. Two different types with this
name exist, but they are unrelated.

ERROR in [at-loader] ./src/main/webapp/app/blocks/interceptor/http.provider.ts:20:9
    TS2345: Argument of type 'XHRBackend' is not assignable to parameter of type 'ConnectionBackend'.
  Types of property 'createConnection' are incompatible.
    Type '(request: Request) => XHRConnection' is not assignable to type '(request: any) => Connection'.
      Type 'XHRConnection' is not assignable to type 'Connection'.
        Types of property 'request' are incompatible.
          Type 'Request' is not assignable to type 'Request'. Two different types with this name exist, but they
 are unrelated.
            Types of property 'headers' are incompatible.
              Type 'Headers' is not assignable to type 'Headers'. Two different types with this name exist, but
they are unrelated.
                Types have separate declarations of a private property 'mayBeSetNormalizedName'.

ERROR in [at-loader] ./src/main/webapp/app/blocks/interceptor/notification.interceptor.ts:5:14
    TS2415: Class 'NotificationInterceptor' incorrectly extends base class 'HttpInterceptor'.
  Types of property 'requestIntercept' are incompatible.
    Type '(options?: RequestOptionsArgs) => RequestOptionsArgs' is not assignable to type '(options?: RequestOpt
ionsArgs) => RequestOptionsArgs'. Two different types with this name exist, but they are unrelated.
      Types of parameters 'options' and 'options' are incompatible.
        Type 'RequestOptionsArgs' is not assignable to type 'RequestOptionsArgs'. Two different types with this
name exist, but they are unrelated.

Have you any idea why this happens?

答:
Finally, it works for me with this way:

ng-jhipster: yarn install, yarn run build (as it is described https://github.com/jhipster/ng-jhipster).

jhipster-project:
Delete the content inside the ng-jhipster (jhipster-project\node_modules\ng-jhipster) and copy the ng-jhipster structure but:

In the 'src' directory(jhipster-project\node_modules\ng-jhipster\src) select all the *.ts files, keep only the *.d.ts and remove all the rest *.ts

delete 'node_modules'(jhipster-project\node_modules\ng-jhipster\node_modules)

Then

yarn (vendor.dll should be regenerated)

yarn start

Is this the way that you work?


问:
JangoSMTP problem with the php mail function
that's right I am back with another php problem I recently asked another question about php mail with smtp2go

I was discouraged about it so I tried getting an email address with 000webhost I set it up with Thunderbird and tested it out

I used jangosmtp as my smtp server (outgoing)

and used 000webhost's incoming as imap it worked fine I could send and receive emails so I then took it to the next level... using php here is my code

send.php:

```<code><html>
<form method="post" action="send.php">
Topic: <br/><input type="text" name="topic"/><br/>
Message: <br/><textarea name="message"></textarea><br/>
<input type="submit" value="Send" name="submit"/>
</form>
</html>
<?php
if ($_POST['submit']){
ini_set("SMTP", "relay.jangosmtp.net");
ini_set("smtp_port", 2525);
$to = "lsworkemail112@gmail.com";
$subj = $_POST['topic'];
$body = $_POST['message'];
$header = "From: lsworkemail112@gmail.com";
if (mail($to, $subj, $body, $header))
{
echo "Message sent successfully";
}
else
{
 echo "Message sent unsuccessfully";
 }
 }
 ?>
</code>```

when I run this code the form appears ok but when I press send

this is what I see

Warning: mail() [function.mail]: SMTP server response: 550 5.7.1
  ... we do not relay  in C:\xampp\htdocs> \send.php on line 16

  Message sent unsuccessfully

I followed these instructions I set up both an ip address and a relay email

lsworkemail112@gmail.com

I tried multiple times with different conbinations of email address but it still did not work

答: Check out http://blog.jangomail.com/2010/11/technical-notes-using-jangomail-api.html and see PHP Sample #2: Send a Transactional Email.  That should eliminate the problem completely. If you still need help, contact our support team: www.jangosmtp.com/Support or 1-888-709-4099. Hope this helps!</p>

Body:
that's right I am back with another php problem I recently asked another question about php mail with smtp2go

I was discouraged about it so I tried getting an email address with 000webhost I set it up with Thunderbird and tested it out

I used jangosmtp as my smtp server (outgoing)

and used 000webhost's incoming as imap it worked fine I could send and receive emails so I then took it to the next level... using php here is my code

send.php:

<form method="post" action="send.php">
Topic:
<input type="text" name="topic"/>

Message:
<textarea name="message"></textarea>

<input type="submit" value="Send" name="submit"/>
</form>

<?php
if ($_POST['submit']){
ini_set("SMTP", "relay.jangosmtp.net");
ini_set("smtp_port", 2525);
$to = "lsworkemail112@gmail.com";
$subj = $_POST['topic'];
$body = $_POST['message'];
$header = "From: lsworkemail112@gmail.com";
if (mail($to, $subj, $body, $header))
{
echo "Message sent successfully";
}
else
{
 echo "Message sent unsuccessfully";
 }
 }
 ?>

when I run this code the form appears ok but when I press send

this is what I see

Warning: mail() [function.mail]: SMTP server response: 550 5.7.1
  ... we do not relay  in C:\xampp\htdocs> \send.php on line 16

  Message sent unsuccessfully

I followed these instructions I set up both an ip address and a relay email

lsworkemail112@gmail.com

I tried multiple times with different conbinations of email address but it still did not work


问:
Change Indexing(Postings)Structure of Lucene
I am doing research on new ways to index documents. Specifically I would like to
change existing index structures to experiment indexing techniques. For example if Lucene has inverted index that saves term and Doc Id's at indexing time, I would like to extend that structure to save other information such as position or statistics about the term. How would I go about making such extensions? Is there a better open source project than Lucene for doing such extensions? Thanks.  </p>

答:
Lucene is a good target, yes (not sure if there is a better option to be honest).

I guess you would end up creating your custom codec. See this blog post, from the main man behind the current codec stuff in modern Lucene. He mentions there the useful SimpleTextCodec that will allow you to understand and play around with codecs. Not for production use, of course.


问:
Whats wrote with this break;
After adding break, my code no longer works.

```<code>alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {while(true)
var a = prompt("Are you ready to enter this game?");
if(a == "yes") {break; alert("Entering");} }
</code>```

答:
You have a few syntax errors in your JavaScript. You are missing out on a curly brace. The break statement needs to be after the alert statement. See the following snippet after the fixes and try to learn your mistakes.

alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {
  while(true) {
    //var b = prompt("Are you ready to enter this game?");
    if(a == "yes") {
        alert("Entering");
        break;
      }
  }
}```

Title: Whats wrote with this break;

Body:
After adding break, my code no longer works.

alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {while(true)
var a = prompt("Are you ready to enter this game?");
if(a == "yes") {break; alert("Entering");} }


问:
Can't run exes made with ocra -- FATAL ERROR: Failed to create process
I'm trying to package a Ruby program as an .exe on a Windows computer using OCRA. When I tried to use it to create the executable for my program, it threw a weird error at runtime. I tried it with a simple Hello World program, and the error persisted.

I put the following in helloworld.rb:

```<code>puts "Hello, World!"
</code>```

Then, I ran the file through OCRA:

```<code>H:\ocra test>ocra --no-dep-run helloworld.rb
=== Detected gem did_you_mean-1.1.0 (loaded, files)
===     14 files, 32780 bytes
=== Detected gem ocra-1.3.8 (loaded, files)
===     5 files, 291748 bytes
=== Including 59 encoding support files (3918740 bytes, use --no-enc to exclude)

=== Building helloworld.exe
=== Adding user-supplied source files
=== Adding ruby executable ruby.exe
=== Adding detected DLL C:/Ruby24-x64/bin/ruby_builtin_dlls/libgmp-10.dll
=== Adding detected DLL C:/Ruby24-x64/bin/ruby_builtin_dlls/libffi-6.dll
=== Adding library files
=== Compressing 7908093 bytes
=== Finished building helloworld.exe (1919669 bytes)
</code>```

However, when I tried to run this executable, I got the following message:

```<code>H:\ocra test>helloworld.exe
FATAL ERROR: Failed to create process (C:\Users\[username]\AppData\Local\Temp\ocr9C6D.tmp\bin\ruby.exe): 14001
</code>```

Note: This is not a duplicate of this person's question which has the same error message. I am unable to run the EXE on the computer that generated it, whereas the person who asked the linked question was having issues running it on other computers.

Here are the versions of Ruby and OCRA, both of which I believe are the latest version:

```<code>H:\ocra test>ruby --version
ruby 2.4.1p111 (2017-03-22 revision 58053) [x64-mingw32]
H:\ocra test>ocra --version
Ocra 1.3.8
</code>```

I'm on Windows 7 Professional 64 bit.

I also tried running it without the --no-dep-run flag, running the exe on my C: drive instead of H:, and running it in a command prompt with local administrator privileges. All gave the same error message.

How do I fix this?

答: I was able to fix the issue by uninstalling Ruby and installing an older version (namely 2.3.3) via RubyInstaller. There seems to be an issue with 2.4.1 and ocra. I tested on a couple of fresh computers, and 2.4.1 didn't work even with a fresh install.</p>

Body:
I'm trying to package a Ruby program as an .exe on a Windows computer using OCRA. When I tried to use it to create the executable for my program, it threw a weird error at runtime. I tried it with a simple Hello World program, and the error persisted.

I put the following in helloworld.rb:

puts "Hello, World!"

Then, I ran the file through OCRA:

H:\ocra test>ocra --no-dep-run helloworld.rb
=== Detected gem did_you_mean-1.1.0 (loaded, files)
===     14 files, 32780 bytes
=== Detected gem ocra-1.3.8 (loaded, files)
===     5 files, 291748 bytes
=== Including 59 encoding support files (3918740 bytes, use --no-enc to exclude)

=== Building helloworld.exe
=== Adding user-supplied source files
=== Adding ruby executable ruby.exe
=== Adding detected DLL C:/Ruby24-x64/bin/ruby_builtin_dlls/libgmp-10.dll
=== Adding detected DLL C:/Ruby24-x64/bin/ruby_builtin_dlls/libffi-6.dll
=== Adding library files
=== Compressing 7908093 bytes
=== Finished building helloworld.exe (1919669 bytes)

However, when I tried to run this executable, I got the following message:

H:\ocra test>helloworld.exe
FATAL ERROR: Failed to create process (C:\Users\[username]\AppData\Local\Temp\ocr9C6D.tmp\bin\ruby.exe): 14001

Note: This is not a duplicate of this person's question which has the same error message. I am unable to run the EXE on the computer that generated it, whereas the person who asked the linked question was having issues running it on other computers.

Here are the versions of Ruby and OCRA, both of which I believe are the latest version:

H:\ocra test>ruby --version
ruby 2.4.1p111 (2017-03-22 revision 58053) [x64-mingw32]
H:\ocra test>ocra --version
Ocra 1.3.8

I'm on Windows 7 Professional 64 bit.

I also tried running it without the --no-dep-run flag, running the exe on my C: drive instead of H:, and running it in a command prompt with local administrator privileges. All gave the same error message.

How do I fix this?


问:
How can I use Conda to install MySQLdb?
I've read several different explanation regarding how to install MySQLdb, but I'm not sure which case applies to me since my error message is different.  My system can't seem to find MySQLdb. I installed pymysql, but i need to import MySQLdb to use procedures from that library.

Thanks for your help.

```<code>$ conda install MySQLdb
</code>```

Fetching package metadata: ....
Error: No packages found in current osx-64 channels matching: mysqldb

Did you mean one of these?

```<code>pymysql
</code>```

You can search for this package on anaconda.org with

```<code>anaconda search -t conda mysqldb

$ anaconda search -t conda mysqldb
</code>```

Using anaconda-server api site https://api.anaconda.org
Run 'anaconda show ' to get more details:
No packages found
     Name                      |  Version | Package Types   | Platforms

     ------------------------- |   ------ | --------------- | ---------------
Found 0 packages

答:
~/anaconda2$ conda install mysql-python

works on ubuntu 16.04

Title: How can I use Conda to install MySQLdb?

Body:
I've read several different explanation regarding how to install MySQLdb, but I'm not sure which case applies to me since my error message is different.  My system can't seem to find MySQLdb. I installed pymysql, but i need to import MySQLdb to use procedures from that library.

Thanks for your help.

$ conda install MySQLdb

Fetching package metadata: ....
Error: No packages found in current osx-64 channels matching: mysqldb

Did you mean one of these?

pymysql

You can search for this package on anaconda.org with

anaconda search -t conda mysqldb

$ anaconda search -t conda mysqldb

Using anaconda-server api site https://api.anaconda.org
Run 'anaconda show ' to get more details:
No packages found
     Name                      |  Version | Package Types   | Platforms

     ------------------------- |   ------ | --------------- | ---------------
Found 0 packages


问:
Rails query interface: selecting rows in database where any of the JSON array's values match a certain criteria
Database info:

Database: PostgresSQL

Table name: publishing_rules

Column name: menu_items

Column format: JSON

Example column value: {"items":[{"id":1,"title":"dfgdfg"},{"id":2,"title":"sdf"}]}

I need to gather all columns which have at least one item  with an id equal to my value. So far I've come up with this:

```<code>    id = 1
    items = PublishingRule.where("menu_items #> '{items,0}' ->> 'id' = ?", id.to_s)
</code>```

However this code only acquires columns with items array first value matching my criteria. I need to modify my code to something similar to:

```<code>    items = PublishingRule.where("menu_items #> '{items, ANY}' ->> 'id' = ?", id.to_s)
</code>```

or

```<code>    id = 1
    items = PublishingRule.where("menu_items #> '{items.map}' ->> 'id' = ?", id.to_s)
</code>```

How do I do that?

答:
Since the items is array at given example you can't work it out using only operators. You need to use jsonb_array_elements() in order to look into that.

Here's SQL query example to meet your requirement:

```<code>SELECT  *
FROM    publishing_rules
WHERE   EXISTS (
            SELECT  1
            FROM    jsonb_array_elements( menu_items -> 'items' )
            WHERE   value ->> 'id' = '2'
            LIMIT   1
        );
</code>```

So, using within WHERE EXISTS lookup into the array does the trick.

Body:
Database info:

Database: PostgresSQL

Table name: publishing_rules

Column name: menu_items

Column format: JSON

Example column value: {"items":[{"id":1,"title":"dfgdfg"},{"id":2,"title":"sdf"}]}

I need to gather all columns which have at least one item  with an id equal to my value. So far I've come up with this:

    id = 1
    items = PublishingRule.where("menu_items #> '{items,0}' ->> 'id' = ?", id.to_s)

However this code only acquires columns with items array first value matching my criteria. I need to modify my code to something similar to:

    items = PublishingRule.where("menu_items #> '{items, ANY}' ->> 'id' = ?", id.to_s)

or

    id = 1
    items = PublishingRule.where("menu_items #> '{items.map}' ->> 'id' = ?", id.to_s)

How do I do that?

Body:
Since the items is array at given example you can't work it out using only operators. You need to use jsonb_array_elements() in order to look into that.

Here's SQL query example to meet your requirement:

SELECT  *
FROM    publishing_rules
WHERE   EXISTS (
            SELECT  1
            FROM    jsonb_array_elements( menu_items -> 'items' )
            WHERE   value ->> 'id' = '2'
            LIMIT   1
        );

So, using within WHERE EXISTS lookup into the array does the trick.


问:
Transmission of data in HTTP
I am trying to understand the basics of the internals of HTTP servers and clients with regards to how they transmit data. I have read many articles about how HTTP works but I haven't found any that answers some of my questions.
I would like to go trough the process of loading a web page as I understand it and I would appreciate if you make me notice where I got it wrong.

When I visit a site my browser asks for an HTML file to a server, for that my browser creates a socket, binds it to my ip adress, and connects it to a listening socket of the server of the site I am visiting. In order to connect my browser's socket to the server I need a port number and a hostname, the port number is 80 because this is HTTP and the hostname is obtained via DNS resolution. Now that there is a connection between sockets my browser sends a GET request. That request is an ASCII file with the contents corresponding to an HTTP request. My browser writes the ASCII raw bytes to the socket and that is written to the server's socket.

The server writes back the HTML file I requested to the socket. The HTML the server sends is just an ASCII file that the server will write byte by byte to the socket.

My browser recieves the ASCII file and parses it. Lets assume here that it finds an image tag. The browser sends an HTTP request for that image file. Here comes something I don't understand. How does the server respond? As far as I can tell the server must send back an ASCII file formed by a set of headers followed by a CRLF and then the body of the message. In this case, assuming my browser asked for a .jpeg, does the server write the headers as ASCII plaintext to the socket and then writes the raw bytes of the image to the socket?

If the HTML file has several images do we open a socket per image (per request)?

Lets assume that my browser now finds a javascript tag. When the server answers to my request for that script does the server writes the ASCII bytes of the source of the script to the socket? What happens with js libraries? Does the server have to send all the source code for each one?

On writing data to the sockets: is write(2) the correct way to do all this writing between sockets?

On the transmission of large files: if I click a button on the site that lets me download a large PDF, how is this accomplished by the server? I assume that the server tries to transmit this in pieces. As far as I can tell there is an option for chunked encoding. Is this the way? If it is, is the file divided into chunks, and these are appended to the ASCII response and written byte by byte into the socket?

Finally, how is video transmitted? I know video encoding and transmission would require entire books for a detailed explanation but if you could say something about the generalities of video transmission (for example in youtube) I would appreciate it.

Anything that you could say about HTTP on the socket level would be appreciated. Thanks.

答:
All my answers below relate to HTTP/1.1, not HTTP/2:

3.-My browser recieves the ASCII file and parses it. Lets assume here that it finds an image tag. The browser sends an HTTP request for that image file. Here comes something I don't understand. How does the server respond? As far as I can tell the server must send back an ASCII file formed by a set of headers followed by a CRLF and then the body of the message. In this case, assuming my browser asked for a .jpeg, does the server write the headers as ASCII plaintext to the socket and then writes the raw bytes of the image to the socket?

yes it does, usually. It's possible that it's encoded in a different format (gzip, brotli) or it might be chunked if a Content-Length was not set.

4.- If the HTML file has several images do we open a socket per image (per request)?

In HTTP/1 modern browsers will open up to 6 sockets per host but not more. If there's more than 6 requests going to the same host, it will wait until the other responses have been received.

5.- Lets asume that my browser now finds a javascript tag. When the server answers to my request for that script does the server writes the ASCII bytes of the source of the script to the socket? What happens with js libraries? Does the server have to send all the source code for each one?

Usually yes, you need 1 http request per javascript file. There's some server-side tools that combine javascript sources along with their dependencies in a single javascript 'file'. Note that javascript sources are typically UTF-8, not ASCII.

6.- On writing data to the sockets: is write(2) the correct way to do all this writing between sockets?

Dunno! Not a C guy

7.- On the transmition of large files: if I click a button on the site that lets me download a large PDF, how is this accomplished by the server? I assume that the server tries to transmit this in pieces. As far as I can tell there is an option for chunked encoding. Is this the way? If it is, is the file divided into chunks, and these are appended to the ASCII response and written byte by byte into the socket?

No, chunked is used for HTTP responses for which the content-length is not known ahead of time. The 'splitting up' you're talking about is done on a IP/TCP level, not at the HTTP protocol level. From a HTTP perspective it's just one continuous stream.

Finally, how is video transmited? I know video encoding and transmition would require entire books for a detailed explanaition but if you could say something about the generalities of video transmition (for example in youtube) I would appreciate it.

Too broad for me to answer.

Title: Transmission of data in HTTP


问:
Firebase Multi Level database handeling in Swift 3
i know how to insert single level data into firebase database. But i want to insert the values and get the values from firebase database with multilevel structure.

I am having dictionary in the structure of [String: [String: [String]]] , i want to insert this value into the table my-test-table with my own key as my-sample-key. then i want to fetch the data using my-sample-key with the same dictionay format.

Is it possible in firebase database?

Thanks.

答:
Good news: It works

```<code>//Save Data
    let myDictionary = [String: [String: [String]]]()

    let ref = FIRDatabase.database().reference().child("allOfMyDictionarys").child("my-sample-key")
    ref.setValue(myDictionary)

    // Recive data
    ref.observe(FIRDataEventType.value) { (snap: FIRDataSnapshot) in
        if let data = snap.value as? [String: [String: [String]]]{
            //Do something here
        }
    }
</code>```

Because Firebase works with JSON like Data structure you dont have things like Tables any more. So you don't need your 'my-test-table' because there is just one file. In order to struct the data I added the 'allOfMyDictionarys' child. Another advantage of the JSON format is you can just save dictionaries of Array without any problems.

Body:
Good news: It works

//Save Data
    let myDictionary = [String: [String: [String]]]()

    let ref = FIRDatabase.database().reference().child("allOfMyDictionarys").child("my-sample-key")
    ref.setValue(myDictionary)

    // Recive data
    ref.observe(FIRDataEventType.value) { (snap: FIRDataSnapshot) in
        if let data = snap.value as? [String: [String: [String]]]{
            //Do something here
        }
    }

Because Firebase works with JSON like Data structure you dont have things like Tables any more. So you don't need your 'my-test-table' because there is just one file. In order to struct the data I added the 'allOfMyDictionarys' child. Another advantage of the JSON format is you can just save dictionaries of Array without any problems.


问:
Turn epoch datetime textbox value to a 24h human date?
I have a first textbox that contains an epoch datetime stamp.

Because this format is not human readable, i decided to set it as readonly and hidden.

From that first textbox value, i would like to mirror its epoch value to a 24h human date that will be visible into a 2sd textbox.

Here is what i did so far, but it does not work :

( ~gpio_actual_schedule_event~ is automatically replaced by a datetime stamp by the server when the page loads )

HTML

```<code><input type="hidden" value="~gpio_actual_schedule_event~" id="epoch_stamp" readonly >
<input type="text" id="converted_set_next_event" readonly >
</code>```

At page load, i convert datetime stamp to human readable format with Javascript :

```<code><script>
function epoch_to_24h_date(){

var epochdate = new Date(~gpio_actual_schedule_event~ * 1); // multiply by 1000 for milliseconds
var date_string = epochdate.toLocaleString('en-GB');  // 24 hour format
    }
</script>

<script>
    window.onload= function(){

          epoch_to_24h_date();
          document.getElementById('converted_set_next_event').value = date_string;

        }
</script>
</code>```

https://jsfiddle.net/lcoulon/0qw06mjs/

答:
The date_string variable is available only inside the epoch_to_24h_date function. You should return it:

```<code><script>
  function epoch_to_24h_date(){
    var epochdate = new Date(~gpio_actual_schedule_event~ * 1); // multiply by 1000 for milliseconds
    return epochdate.toLocaleString('en-GB');  // 24 hour format
  }
</script>

<script>
  window.onload= function(){
    document.getElementById('converted_set_next_event').value = epoch_to_24h_date();
  }
</script>
</code>```

Body:
I have a first textbox that contains an epoch datetime stamp.

Because this format is not human readable, i decided to set it as readonly and hidden.

From that first textbox value, i would like to mirror its epoch value to a 24h human date that will be visible into a 2sd textbox.

Here is what i did so far, but it does not work :

( ~gpio_actual_schedule_event~ is automatically replaced by a datetime stamp by the server when the page loads )

HTML

<input type="hidden" value="~gpio_actual_schedule_event~" id="epoch_stamp" readonly >
<input type="text" id="converted_set_next_event" readonly >

At page load, i convert datetime stamp to human readable format with Javascript :

https://jsfiddle.net/lcoulon/0qw06mjs/

Body:
The date_string variable is available only inside the epoch_to_24h_date function. You should return it:

<script>
  function epoch_to_24h_date(){
    var epochdate = new Date(~gpio_actual_schedule_event~ * 1); // multiply by 1000 for milliseconds
    return epochdate.toLocaleString('en-GB');  // 24 hour format
  }
</script>

<script>
  window.onload= function(){
    document.getElementById('converted_set_next_event').value = epoch_to_24h_date();
  }
</script>


问:
com.google.api.config.ServiceConfigSupplier - Failed to fetch default config version for service (only on localhost)
I'm using Cloud Endpoints Frameworks (2.0.1) for Java as part of my final year project and have been relatively successful with it so far.
I don't have any problems when deploying to my appspot.com domain, however, I am running into some problems when deploying locally.

(Any references to my-project-id in the following code blocks are aliases for my actual google cloud project id)

I have a valid openapi descriptor (openapi.json) of an annotated @API class which I am deploying to cloud endpoints using "gcloud service-management deploy openapi.json".
The command returns successfully:

```<code>Service Configuration [2017-02-23r0] uploaded for service [api.endpoints.<my-project-id>.cloud.goog]
</code>```

I then map the returned config_id to the correct endpoints_api_service in my app.yaml

```<code>endpoints_api_service:
  name: api.endpoints.<my-project-id>.cloud.goog
  config_id: 2017-02-23r0
</code>```

This service is listed by the gcloud cli tool using "gcloud service-management list"

```<code>    NAME                                                           TITLE
    storage-component.googleapis.com                 Google Cloud Storage
    api.endpoints.<my-project-id>.cloud.goog         api.endpoints.<my-project-id>.cloud.goog
    etc...
</code>```

and "gcloud service-management configs list --service api.endpoints.my-project-id.cloud.goog"

```<code>CONFIG_ID        SERVICE_NAME
2017-02-23r0     api.endpoints.<my-project-id>.cloud.goog
... other version configs
</code>```

and is accessible on my appspot.com domain (I can call the endpoint and receive the correct response)

I am trying to deploy my project on localhost using the maven appengine plugin for java (mvn appengine:devserver), but upon jetty startup I'm hit with the following Exception:

```<code> WARNING: Failed startup of context com.google.appengine.tools.development.DevAppEngineWebAppContext...

com.google.api.config.ServiceConfigException: Failed to fetch default config version for service 'api.endpoints.<my-project-id>.cloud.goog'. No versions exist!
at com.google.api.config.ServiceConfigSupplier.fetchLatestServiceVersion(ServiceConfigSupplier.java:155)
....
</code>```

The deployment then gets stuck in an endless cycle of trying to start jetty, and being hit with that error message, and restarting etc. Any attempts to access localhost:8080 result in a "503: Service not found" error

I assumed that the local deployment of my app would be able to access the service config that was deployed using "gcloud service-management deploy", in the same way that the appspot.com deployment can, but is this not the case?
Looking at the source for ServiceConfigSupplier.getchLatestServiceVersion() I gather that serviceManagement.services().configs().list(my-service-name).execute().getServiceConfigs() is returning an empty list, but why is this only occurring locally?

Extra Information

my ENDPOINTS_SERVICE_NAME environment variable matches 'api.endpoints.my-project-id.cloud.goog'

I noticed that there was an update (1.0.2) to com.google.api.config a few days ago, and it has a dependency on an older version of com.google.api.services.servicemanagement (dependent on v1-rev14-1.22.0 with the newest version being v1-rev340-1.22.0)
I doubt this is the problem, but I thought I would mention it, as it contains classes relevant to the exception (ServiceManagement is used by ServiceConfigSupplier, which is throwing the exception). Perhaps there is an inconsistency in where they are looking for the service configs?

I'm quite stumped tbh, it's a bit over my head. I would dislike having to remove Endpoints, as I'm starting to like it, but we also can't really lose usage of our devserver either. I hope someone can shed a little bit of light on this issue.

答:
It worked with "gradle appengineRun" but on IntelliJ Idea project I had to replace all the ${endpoints.project.id} in web.xml and appengine-web.xml to run/debug localhost from IntelliJ (imported from gradle sources, installed Google Cloud Tools plugin and set up run/debug configuration from Tools/GoogleCloudTools/Run on a local App Engine Standard dev server).

My error was:
Failed to fetch default config version for service 'echo-api.endpoints.${endpoints.project.id}.cloud.goog'. No versions exist!

cloud.google.com docs only have Maven build example Gradle build is at github.com

Body:
I'm using Cloud Endpoints Frameworks (2.0.1) for Java as part of my final year project and have been relatively successful with it so far.
I don't have any problems when deploying to my appspot.com domain, however, I am running into some problems when deploying locally.

(Any references to my-project-id in the following code blocks are aliases for my actual google cloud project id)

I have a valid openapi descriptor (openapi.json) of an annotated @API class which I am deploying to cloud endpoints using "gcloud service-management deploy openapi.json".
The command returns successfully:

Service Configuration [2017-02-23r0] uploaded for service [api.endpoints.<my-project-id>.cloud.goog]

I then map the returned config_id to the correct endpoints_api_service in my app.yaml

endpoints_api_service:
  name: api.endpoints.<my-project-id>.cloud.goog
  config_id: 2017-02-23r0

This service is listed by the gcloud cli tool using "gcloud service-management list"

    NAME                                                           TITLE
    storage-component.googleapis.com                 Google Cloud Storage
    api.endpoints.<my-project-id>.cloud.goog         api.endpoints.<my-project-id>.cloud.goog
    etc...

and "gcloud service-management configs list --service api.endpoints.my-project-id.cloud.goog"

CONFIG_ID        SERVICE_NAME
2017-02-23r0     api.endpoints.<my-project-id>.cloud.goog
... other version configs

and is accessible on my appspot.com domain (I can call the endpoint and receive the correct response)

I am trying to deploy my project on localhost using the maven appengine plugin for java (mvn appengine:devserver), but upon jetty startup I'm hit with the following Exception:

 WARNING: Failed startup of context com.google.appengine.tools.development.DevAppEngineWebAppContext...

com.google.api.config.ServiceConfigException: Failed to fetch default config version for service 'api.endpoints.<my-project-id>.cloud.goog'. No versions exist!
at com.google.api.config.ServiceConfigSupplier.fetchLatestServiceVersion(ServiceConfigSupplier.java:155)
....

The deployment then gets stuck in an endless cycle of trying to start jetty, and being hit with that error message, and restarting etc. Any attempts to access localhost:8080 result in a "503: Service not found" error

I assumed that the local deployment of my app would be able to access the service config that was deployed using "gcloud service-management deploy", in the same way that the appspot.com deployment can, but is this not the case?
Looking at the source for ServiceConfigSupplier.getchLatestServiceVersion() I gather that serviceManagement.services().configs().list(my-service-name).execute().getServiceConfigs() is returning an empty list, but why is this only occurring locally?

Extra Information

my ENDPOINTS_SERVICE_NAME environment variable matches 'api.endpoints.my-project-id.cloud.goog'

I noticed that there was an update (1.0.2) to com.google.api.config a few days ago, and it has a dependency on an older version of com.google.api.services.servicemanagement (dependent on v1-rev14-1.22.0 with the newest version being v1-rev340-1.22.0)
I doubt this is the problem, but I thought I would mention it, as it contains classes relevant to the exception (ServiceManagement is used by ServiceConfigSupplier, which is throwing the exception). Perhaps there is an inconsistency in where they are looking for the service configs?

I'm quite stumped tbh, it's a bit over my head. I would dislike having to remove Endpoints, as I'm starting to like it, but we also can't really lose usage of our devserver either. I hope someone can shed a little bit of light on this issue.


问:
How can I get information from a select with angularjs and ionic1?
How can I get information from a select with angularjs and ionic1?

I'm trying to get the information from a JSON and put in the "select", until that part I got to do. But when I select the information from this "select" and try to get the id and the name that is in the "select", it is not showing.

My html -> igreja.html

```<code><ion-view view-title="Igrejas">
    <ion-nav-buttons side="left">
            <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
            </button>
    </ion-nav-buttons>
    <ion-content>
     <form ng-submit="realizarLogin()">
      <div class="list list-inset">
        <ion-item class="item-input item-select--full">
          <div class="input-label">
            Selecione a sua igreja
          </div>
          <select ng-model="login" ng-options="y.Nome for (x,y) in igrejaEscolhida">
          </select>
          <h1> test: {{login.Nome}}</h1>
          <h1> id: {{login.Id}} </h1>
        </ion-item>

        <button class="button button-block button-positive" type="submit">Entrar</button>
      </div>
    </form>
    </ion-content>
</ion-view>
</code>```

My routes.js

```<code>.state('app.igrejas', {
    url: '/igrejas',
    views: {
      'menuContent': {
        templateUrl: 'templates/igrejas.html',
        controller: 'igrejasController'
      }
    }
  })
</code>```

My controller.js

```<code>.controller('igrejasController', function($scope, $ionicModal, $timeout, $stateParams, $ionicPopup, $state, $rootScope, $http, $sce) {

  $http.get(linkIgrejas).then(function(data){

    $scope.igrejaEscolhida = data.data;

    console.log($scope.igrejaEscolhida);

    $scope.igrejaEscolhida.forEach(function(element, index, array){
      element.Id = element.Id;
      element.Nome = element.Nome;
      console.log(element.Id);
      console.log(element.Nome);
    })

  })

  $rootScope.login = {};

  $scope.realizarLogin = function() {

    var dadosDoLogin = {
      params : {
        nome: $rootScope.login.nome
      }
    }

    $scope.selectUpdated = function(optionSelected) {

      console.log('Updated');
      console.log(optionSelected);

    };

    console.log($scope.selectUpdated);

    $scope.loginF.Nome;
    $scope.loginF.Id;

    console.log($scope.loginF.Nome);
    console.log($scope.loginF.Id);

     $rootScope.teste = $rootScope.login.nome;
     $scope.nomeIgreja = $rootScope.login.nome;
     $scope.idIgreja = $rootScope.login.Id;

     $rootScope.login.Id;

      console.log($scope.nomeIgreja);
      console.log($scope.idIgreja);

  };
})
</code>```

Could someone help me or show me what I'm doing wrong in the "select"?

答:
Try to put the value itself to represent The id

```<code><option ng-repeat="igrejaEscolhidas in igrejaEscolhida" value="{{ igrejaEscolhidas.Id }}">
                   {{ igrejaEscolhidas.Nome  }}
                  </option>
</code>```

then the ng-model with the select will take the Id from the value of the selected option.

Body:
How can I get information from a select with angularjs and ionic1?

I'm trying to get the information from a JSON and put in the "select", until that part I got to do. But when I select the information from this "select" and try to get the id and the name that is in the "select", it is not showing.

My html -> igreja.html

<ion-view view-title="Igrejas">
    <ion-nav-buttons side="left">
            <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
            </button>
    </ion-nav-buttons>
    <ion-content>
     <form ng-submit="realizarLogin()">

        <ion-item class="item-input item-select--full">

            Selecione a sua igreja

          <select ng-model="login" ng-options="y.Nome for (x,y) in igrejaEscolhida">
          </select>

 test: {{login.Nome}}

 id: {{login.Id}}

        </ion-item>

        <button class="button button-block button-positive" type="submit">Entrar</button>

    </form>
    </ion-content>
</ion-view>

My routes.js

.state('app.igrejas', {
    url: '/igrejas',
    views: {
      'menuContent': {
        templateUrl: 'templates/igrejas.html',
        controller: 'igrejasController'
      }
    }
  })

My controller.js

.controller('igrejasController', function($scope, $ionicModal, $timeout, $stateParams, $ionicPopup, $state, $rootScope, $http, $sce) {

  $http.get(linkIgrejas).then(function(data){

    $scope.igrejaEscolhida = data.data;

    console.log($scope.igrejaEscolhida);

    $scope.igrejaEscolhida.forEach(function(element, index, array){
      element.Id = element.Id;
      element.Nome = element.Nome;
      console.log(element.Id);
      console.log(element.Nome);
    })

  })

  $rootScope.login = {};

  $scope.realizarLogin = function() {

    var dadosDoLogin = {
      params : {
        nome: $rootScope.login.nome
      }
    }

    $scope.selectUpdated = function(optionSelected) {

      console.log('Updated');
      console.log(optionSelected);

    };

    console.log($scope.selectUpdated);

    $scope.loginF.Nome;
    $scope.loginF.Id;

    console.log($scope.loginF.Nome);
    console.log($scope.loginF.Id);

     $rootScope.teste = $rootScope.login.nome;
     $scope.nomeIgreja = $rootScope.login.nome;
     $scope.idIgreja = $rootScope.login.Id;

     $rootScope.login.Id;

      console.log($scope.nomeIgreja);
      console.log($scope.idIgreja);

  };
})

Could someone help me or show me what I'm doing wrong in the "select"?

Body:
Try to put the value itself to represent The id

<option ng-repeat="igrejaEscolhidas in igrejaEscolhida" value="{{ igrejaEscolhidas.Id }}">
                   {{ igrejaEscolhidas.Nome  }}
                  </option>

then the ng-model with the select will take the Id from the value of the selected option.


问:
unity3d c# typing to file fast
I want to save what I type to a text file. The code bellow works but when I type too fast, the file has no time to include all the character typed.
Would anyone have a suggestion on how to solve this?</p>

```<code>using System.IO;

string inp;

void Update ()
{
    if
    (
        Input.anyKeyDown
    )
    {

        inp=inp+(string)Input.inputString;

        string path="txt/txttst001.txt";

            File.WriteAllText
            (
                path,
                inp
            );
    }
}
</code>```

答:
Try changing a Fixed Timestep to lower value in Time Manager and using FixedUpdate instead of Update.

https://docs.unity3d.com/Manual/class-TimeManager.html

Title: unity3d c# typing to file fast

Body:
I want to save what I type to a text file. The code bellow works but when I type too fast, the file has no time to include all the character typed.
Would anyone have a suggestion on how to solve this?

using System.IO;

string inp;

void Update ()
{
    if
    (
        Input.anyKeyDown
    )
    {

        inp=inp+(string)Input.inputString;

        string path="txt/txttst001.txt";

            File.WriteAllText
            (
                path,
                inp
            );
    }
}


问:
How to merge two rows from a table into one in Oracle?
I have a table with the following columns and values.

```<code>Name Rate Kind NoOfItems TotalAmount
---- ---- ---- --------- -----------
ABC     1 O           50          50
ABC     2 A           10          20
</code>```

(*) Table will have N names and the kind will be either O or A

I have to output the above table data as follows into a single row for each and every name.

```<code>Name O_Rate A_Rate O_Items A_Items O_Amount A_Amount TotalItems TotalAmount
---- ------ ------ ------- ------- -------- -------- ---------- -----------
ABC       1      2      50      10       50       20         60          70
</code>```

How to convert the above mentioned table data as per the expected output using a single query. I have tried with Case and Decode but in both cases I am getting two rows only.

Thanks in advance.

答:
Since Oracle 11.1 (I think) you can use the PIVOT operator, as shown below.

Better: it seems your so-called "input" is in fact an intermediate result, the output of other data processing. If so, you may be able to combine the PIVOT operation with what you are already doing - there is no reason to have it as a separate step, duplicating some of the work (and therefore some of the execution time). If you can show how you got the so-called "input" in the first place, we can show you how to integrate it with pivoting.

```<code>with
     test_data ( name, rate, kind, noofitems, totalamount ) as (
                 select 'ABC', 1, 'O', 50, 50 from dual
       union all select 'ABC', 2, 'A', 10, 20 from dual
     )
-- End of test data (not part of the solution).
-- SQL query begins BELOW THIS LINE.
select name, o_rate, a_rate, o_noofitems as o_items, a_noofitems as a_items,
       o_totalamount as o_amount, a_totalamount as a_amount,
       o_noofitems + a_noofitems as totalitems,
       o_totalamount + a_totalamount as totalamount
from   test_data
pivot(
       max(rate) as rate, max(noofitems) as noofitems, max(totalamount) as totalamount
       for kind in ('O' as o, 'A' as a)
     )
;

NAME  O_RATE  A_RATE  O_ITEMS  A_ITEMS  O_AMOUNT  A_AMOUNT  TOTALITEMS  TOTALAMOUNT
----  ------  ------  -------  -------  --------  --------  ----------  -----------
ABC        1       2       50       10        50        20          60           70
</code>```

Body:
I have a table with the following columns and values.

Name Rate Kind NoOfItems TotalAmount
---- ---- ---- --------- -----------
ABC     1 O           50          50
ABC     2 A           10          20

(*) Table will have N names and the kind will be either O or A

I have to output the above table data as follows into a single row for each and every name.

Name O_Rate A_Rate O_Items A_Items O_Amount A_Amount TotalItems TotalAmount
---- ------ ------ ------- ------- -------- -------- ---------- -----------
ABC       1      2      50      10       50       20         60          70

How to convert the above mentioned table data as per the expected output using a single query. I have tried with Case and Decode but in both cases I am getting two rows only.

Thanks in advance.

Body:
Since Oracle 11.1 (I think) you can use the PIVOT operator, as shown below.

Better: it seems your so-called "input" is in fact an intermediate result, the output of other data processing. If so, you may be able to combine the PIVOT operation with what you are already doing - there is no reason to have it as a separate step, duplicating some of the work (and therefore some of the execution time). If you can show how you got the so-called "input" in the first place, we can show you how to integrate it with pivoting.

with
     test_data ( name, rate, kind, noofitems, totalamount ) as (
                 select 'ABC', 1, 'O', 50, 50 from dual
       union all select 'ABC', 2, 'A', 10, 20 from dual
     )
-- End of test data (not part of the solution).
-- SQL query begins BELOW THIS LINE.
select name, o_rate, a_rate, o_noofitems as o_items, a_noofitems as a_items,
       o_totalamount as o_amount, a_totalamount as a_amount,
       o_noofitems + a_noofitems as totalitems,
       o_totalamount + a_totalamount as totalamount
from   test_data
pivot(
       max(rate) as rate, max(noofitems) as noofitems, max(totalamount) as totalamount
       for kind in ('O' as o, 'A' as a)
     )
;

NAME  O_RATE  A_RATE  O_ITEMS  A_ITEMS  O_AMOUNT  A_AMOUNT  TOTALITEMS  TOTALAMOUNT
----  ------  ------  -------  -------  --------  --------  ----------  -----------
ABC        1       2       50       10        50        20          60           70


问:
Large, persistent DataFrame in pandas
I am exploring switching to python and pandas as a long-time SAS user.

However, when running some tests today, I was surprised that python ran out of memory when trying to pandas.read_csv() a 128mb csv file.  It had about 200,000 rows and 200 columns of mostly numeric data.

With SAS, I can import a csv file into a SAS dataset and it can be as large as my hard drive.

Is there something analogous in pandas?

I regularly work with large files and do not have access to a distributed computing network.

答:
If you want to load huge csv files, dask might be a good option. It mimics the pandas api, so it feels quite similar to pandas

link to dask on github

Title: Large, persistent DataFrame in pandas


问:
pynput Keyboard Listener returns shift when shift is pressed, but does not modify shift_pressed
I've got a simple program to familiarize myself with Keyboard Listeners using pynput. What it does is not important. What is important is that the shift_pressed attribute never seems to change to True. My program currently looks like this:

```<code>from pynput.keyboard import Controller, Listener

boo = True
keyboard = Controller()

fib_lst = [0, 1]

def on_press(key):
    print(key)
    print(keyboard.shift_pressed)

Listener(on_press=on_press).start()

while boo:
    nxt = fib_lst[-1] + fib_lst[-2]
    input(nxt)
    fib_lst.append(nxt)
</code>```

I'm trying to do something like this in on_press (or on_release):

```<code>def on_press(key):
    if key == Key.delete:
        if keyboard.shift_pressed:
            func1()

        else:
            func2()
</code>```

This code should perform func1 when shift is pressed or func2 if it is not. But it is currently only doing func2 since shift_pressed is perpetually false. What can I do differently to get shift_pressed to work as it should?

Edit 1: Specified the desired end result more clearly.

Edit 2: Changed the appending string to two different functions to add more clarity.

Edit 3: Changed the parameters of the final question to match the more recent example

答:
This is a bug in the pynput 1.3.5 documentation.

The various modifier state properties (alt_pressed, alt_gr_pressed, ctrl_pressed and shift_pressed) reflect only the state of the Controller instance; it maintains an inner modifier state which is applied when various keys are pressed---for example to uppercase characters from scripts that support it.

This state is separate from the current operating system state and will only change when you send key presses using that specific controller.

There is no general pynput method to retrieve the current global modifier state.

Body:
I've got a simple program to familiarize myself with Keyboard Listeners using pynput. What it does is not important. What is important is that the shift_pressed attribute never seems to change to True. My program currently looks like this:

from pynput.keyboard import Controller, Listener

boo = True
keyboard = Controller()

fib_lst = [0, 1]

def on_press(key):
    print(key)
    print(keyboard.shift_pressed)

Listener(on_press=on_press).start()

while boo:
    nxt = fib_lst[-1] + fib_lst[-2]
    input(nxt)
    fib_lst.append(nxt)

I'm trying to do something like this in on_press (or on_release):

def on_press(key):
    if key == Key.delete:
        if keyboard.shift_pressed:
            func1()

        else:
            func2()

This code should perform func1 when shift is pressed or func2 if it is not. But it is currently only doing func2 since shift_pressed is perpetually false. What can I do differently to get shift_pressed to work as it should?

Edit 1: Specified the desired end result more clearly.

Edit 2: Changed the appending string to two different functions to add more clarity.

Edit 3: Changed the parameters of the final question to match the more recent example


问:
Insert object in list c++
I have this class:

```<code>class UserLogRecord
{
public:
  std::string timestamp;
  std::string id;
  std::string name;
  std::string data;
};
</code>```

I'm iterating one vector of strings that have my logData and for each iteration i'm saving to my list.

```<code>std::vector<std::string> lines = explode(filedata,'\n');
std::list<UserLogRecord* > userLogRecords;
UserLogRecord* userLogRecord = new UserLogRecord;

//vector
for(int i = 0; i < lines.size(); i++)
{
  std::vector<std::string> elements = explode(lines[i], ';');
  userLogRecord->timestamp = elements.at(0);
  userLogRecord->id = elements.at(5);
  userLogRecord->name = elements.at(6);
  userLogRecord->data = elements.at(3);
  userLogRecords.push_back(userLogRecord);
}
</code>```

The Explode function is an auxiliary function to parse filedata. My filedata only have two logs, so the for loop runs two times. After that, if I iterate through my list and show, for example, timestamp and id, it shows me 2 times, but the same log (the last one with the same timestamp, same id).

I'm new to C++, but what is wrong? I need to change my UserLogRecord to include a constructor and add elements to my class inside the loop like this:

```<code>UserLogRecord* userLogRecord = new UserLogRecord(elements.at(0), elements.at(5), elements.at(6), elements.at(3));
</code>```

And then use push_back to add userLogRecord to the list? Or should my first implementation work, but I'm doing something wrong?

答: Your first method should work; thought, you might want to post the expected/actual output. Its quite hard to debug without those, if you coded explode yourself perhaps, post that code as well as it could possibly be the cause of your problems.

Title: Insert object in list c++

Body:
I have this class:

class UserLogRecord
{
public:
  std::string timestamp;
  std::string id;
  std::string name;
  std::string data;
};

I'm iterating one vector of strings that have my logData and for each iteration i'm saving to my list.

std::vector<std::string> lines = explode(filedata,'\n');
std::list<UserLogRecord* > userLogRecords;
UserLogRecord* userLogRecord = new UserLogRecord;

//vector
for(int i = 0; i < lines.size(); i++)
{
  std::vector<std::string> elements = explode(lines[i], ';');
  userLogRecord->timestamp = elements.at(0);
  userLogRecord->id = elements.at(5);
  userLogRecord->name = elements.at(6);
  userLogRecord->data = elements.at(3);
  userLogRecords.push_back(userLogRecord);
}

The Explode function is an auxiliary function to parse filedata. My filedata only have two logs, so the for loop runs two times. After that, if I iterate through my list and show, for example, timestamp and id, it shows me 2 times, but the same log (the last one with the same timestamp, same id).

I'm new to C++, but what is wrong? I need to change my UserLogRecord to include a constructor and add elements to my class inside the loop like this:

UserLogRecord* userLogRecord = new UserLogRecord(elements.at(0), elements.at(5), elements.at(6), elements.at(3));

And then use push_back to add userLogRecord to the list? Or should my first implementation work, but I'm doing something wrong?


问:
JavaScript Program Path Not Specified Error
I've been creating a JavaScript game for a project recently and have done it completely on the CodePen website. I now am trying to transfer it to WebStorm to turn it into a basic website. However when I try to run my code I get the following error:

I don't know how to fix it, I've looked everywhere and haven't been able to get some help. Any information would be appreciated.

答: Simple one, basically the error says, I don't know how to interpret this bit of code that you just gave me. You're missing local install of Node.js and NPM. Get the latest versions of these 2, and then go to File -> Settings -> Language&Frameworks -> Node.js and NPM and in the Node interpreter text box, point it to the path of where node.js was installed. </p>