问:
pandas resample changes numerical value of index
Background: I'm trying to plot dissimilar pd.Series on the same axes. One of the Series has a much higher data rate, so I want to filter it (series.resample) and reduce the noise. The problem is, after resampling, it no longer plots on top of the low-data-rate Series.

EDIT: In addition, the data have different y-axis scales, so I'm using secondary_y=True. This somehow seems to be important, but I'm not sure why.

Proximate cause: I realized that the automatic x-axis limits coming back from matplotlib are very different after resampling. This means that the underlying numerical value of the index is changing. But I can't find anything in the pandas documentation about this.

EDIT: The xlim() output in the following code snippet demonstrates the change of x-axis limits. @masasa below points out that by issuing the plot commands together, both ds and ds_filt will plot successfully on the same axes. This is true even with secondary_y=True. However, my other Series does not plot successfully with ds_filt (not shown here because I don't even know how to reproduce the failure).

```<code>import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

idx = pd.date_range('20190101', '20190103', freq='10s')
arr = np.random.randn(idx.size).cumsum()
ds = pd.Series(index=idx, data=arr)

ds.plot()
plt.xlim()

>>> (1546300800.0, 1546473600.0)

ds_filt = ds.resample('12H').mean()
ds_filt.plot()
plt.xlim()

>>> (429528.0, 429576.0)
</code>```

答:
I might didnt understand your problem correctly , but your 2 plots are not on the same figure, thats why they are seperated,
if you do the following :

```<code>ds.plot()
ds.resample('12H').mean().plot()
plt.xlim()
</code>```

youll get a merged graph

Body:
Background: I'm trying to plot dissimilar pd.Series on the same axes. One of the Series has a much higher data rate, so I want to filter it (series.resample) and reduce the noise. The problem is, after resampling, it no longer plots on top of the low-data-rate Series.

EDIT: In addition, the data have different y-axis scales, so I'm using secondary_y=True. This somehow seems to be important, but I'm not sure why.

Proximate cause: I realized that the automatic x-axis limits coming back from matplotlib are very different after resampling. This means that the underlying numerical value of the index is changing. But I can't find anything in the pandas documentation about this.

EDIT: The xlim() output in the following code snippet demonstrates the change of x-axis limits. @masasa below points out that by issuing the plot commands together, both ds and ds_filt will plot successfully on the same axes. This is true even with secondary_y=True. However, my other Series does not plot successfully with ds_filt (not shown here because I don't even know how to reproduce the failure).

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

idx = pd.date_range('20190101', '20190103', freq='10s')
arr = np.random.randn(idx.size).cumsum()
ds = pd.Series(index=idx, data=arr)

ds.plot()
plt.xlim()

>>> (1546300800.0, 1546473600.0)

ds_filt = ds.resample('12H').mean()
ds_filt.plot()
plt.xlim()

>>> (429528.0, 429576.0)

Body:
I might didnt understand your problem correctly , but your 2 plots are not on the same figure, thats why they are seperated,
if you do the following :

ds.plot()
ds.resample('12H').mean().plot()
plt.xlim()

youll get a merged graph


来源: stackexchange

问:
How to get Distinct List
I found online soluton like this:

```<code>import 'package:queries/collections.dart';

void main() {
  List<String> list = ["a", "a", "b", "c", "b", "d"];
  var result = new Collection(list).distinct();
  print(result.toList());
}
</code>```

But, I don't know how to convert var result back to List<Widget>.

答:
Thank you for your answer,
Here is the full code, i try to modify your method but not working.
(Works only in print) </p>

```<code>      Future<List<List<Widget>>> getList(List<int> list, String column) async {

    List<Widget> list1 = List();
    List<Widget> list2 = List();
    List<Widget> list3 = List();

    //test
  List<String> testlista = List();
  testlista.add(result[0][column].toString());

    List<List<Widget>> listFromDB = [list1, list2, list3];
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'books.db');
    Database database = await openDatabase(path, version: 1);
    for (int i = 0; i < list.length; i++) {

      var result = await database.rawQuery(
          'SELECT DISTINCT $column FROM planner WHERE id = ${list[i]}');

    //here polulate new List
    testlista.add(result[0][column].toString());

      if (list[i] < 18) list1.add(_item(result[0][column].toString()));
      if (list[i] > 17 && list[i] < 50)
        list2.add(_item(result[0][column].toString()));
      if (list[i] > 49) list3.add(_item(result[0][column].toString()));
    }

  //Now this give me corect print list without duplicate!!!
  for (int i = 0; i < testlista.length-1; i++) {
  print('FROM DELETE method: '+ deleteDuplicate(testlista)[i]);

}

    await database.close();
    return listFromDB;
  }

   //Method for removingDuplicate

   List<String> deleteDuplicate(List<String> lista) {
    // List<String> result = Set.from(lista).toList();
    List<String> result = {...lista}.toList();
    return result;
  }
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get Distinct List

Body:
I found online soluton like this:

import 'package:queries/collections.dart';

void main() {
  List<String> list = ["a", "a", "b", "c", "b", "d"];
  var result = new Collection(list).distinct();
  print(result.toList());
}

But, I don't know how to convert var result back to List<Widget>.

Body:
Thank you for your answer,
Here is the full code, i try to modify your method but not working.
(Works only in print)

      Future<List<List<Widget>>> getList(List<int> list, String column) async {

    List<Widget> list1 = List();
    List<Widget> list2 = List();
    List<Widget> list3 = List();

    //test
  List<String> testlista = List();
  testlista.add(result[0][column].toString());

    List<List<Widget>> listFromDB = [list1, list2, list3];
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'books.db');
    Database database = await openDatabase(path, version: 1);
    for (int i = 0; i < list.length; i++) {

      var result = await database.rawQuery(
          'SELECT DISTINCT $column FROM planner WHERE id = ${list[i]}');

    //here polulate new List
    testlista.add(result[0][column].toString());

      if (list[i] < 18) list1.add(_item(result[0][column].toString()));
      if (list[i] > 17 && list[i] < 50)
        list2.add(_item(result[0][column].toString()));
      if (list[i] > 49) list3.add(_item(result[0][column].toString()));
    }

  //Now this give me corect print list without duplicate!!!
  for (int i = 0; i < testlista.length-1; i++) {
  print('FROM DELETE method: '+ deleteDuplicate(testlista)[i]);

}

    await database.close();
    return listFromDB;
  }

   //Method for removingDuplicate

   List<String> deleteDuplicate(List<String> lista) {
    // List<String> result = Set.from(lista).toList();
    List<String> result = {...lista}.toList();
    return result;
  }


问:
How to fix "Error: Could not find the implementation for builder @angular-devkit/build-angular:dev-server"
I upgrade my angular project to angular 8 and now when I type

```<code>ng serve
</code>```

I receive this error:

Error: Could not find the implementation for builder @angular-devkit/build-angular:dev-server

For the upgrade I used ng update. When I type

```<code>ng update
</code>```

I get:

Using package manager: 'npm'

Collecting installed dependencies...

Found 41 dependencies.

We analyzed your package.json and everything seems to be in order. Good work!

答:
Maybe this'll help</p>

```<code>npm install --save-dev @angular-devkit/build-angular
</code>```

Body:
I upgrade my angular project to angular 8 and now when I type

ng serve

I receive this error:

Error: Could not find the implementation for builder @angular-devkit/build-angular:dev-server

For the upgrade I used ng update. When I type

ng update

I get:

Using package manager: 'npm'

Collecting installed dependencies...

Found 41 dependencies.

We analyzed your package.json and everything seems to be in order. Good work!

Body:
Maybe this'll help

npm install --save-dev @angular-devkit/build-angular


问:
show multiple password fields with single checkbox
I am trying to make a code that shows multiple password fields into text.
Here is the approach that I made, my focus is on making the code as short as possible, but it seems like am doing something wrong with the approaches that I took.

Approach 1:

```<code><input type="password" class="password">
<input type="password" class="password">
<input type="checkbox" onchange="document.getElementByClassName('.password').type = this.checked ? 'text' : 'password'"> Show password
</code>```

Above Approach is working perfectly if I use getElementById but not with getElementByClassName

Approach 2: fiddle

```<code>Password: <input type="password" value="FakePSW" id="myInput"><br><br>
<input type="checkbox" onclick="myFunction()">Show Password
<script>
function myFunction() {
  var x = document.getElementById("myInput");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
</script>
</code>```

The same issue happens with this approach as well if using getElementByClassName instead.

答:
You should use getElementsByClassName instead of getElementByClassName

getElementsByClassName returns an HTMLCollection. You can use for to loop thru

function toogleInput(e) {
  var list = document.getElementsByClassName('password');
  for (let item of list) {
    item.type = e.checked ? 'text' : 'password';
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="password" class="password">
<input type="password" class="password">
<input type="checkbox" onchange="toogleInput(this)"> Show password</code>```

In case you want jQuery you can use attr()

$(".toggle-password").change(function() {
  $(".password").attr("type", this.checked ? "text" : "password")
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" class="password">
<input type="password" class="password">
<input type="checkbox" class="toggle-password"> Show password</code>```

Body:
I am trying to make a code that shows multiple password fields into text.
Here is the approach that I made, my focus is on making the code as short as possible, but it seems like am doing something wrong with the approaches that I took.

Approach 1:

<input type="password" class="password">
<input type="password" class="password">
<input type="checkbox" onchange="document.getElementByClassName('.password').type = this.checked ? 'text' : 'password'"> Show password

Above Approach is working perfectly if I use getElementById but not with getElementByClassName

Approach 2: fiddle

Password: <input type="password" value="FakePSW" id="myInput">

<input type="checkbox" onclick="myFunction()">Show Password

The same issue happens with this approach as well if using getElementByClassName instead.

Body:
You should use getElementsByClassName instead of getElementByClassName

getElementsByClassName returns an HTMLCollection. You can use for to loop thru

function toogleInput(e) {
  var list = document.getElementsByClassName('password');
  for (let item of list) {
    item.type = e.checked ? 'text' : 'password';
  }
}

<input type="password" class="password">
<input type="password" class="password">
<input type="checkbox" onchange="toogleInput(this)"> Show password

In case you want jQuery you can use attr()

$(".toggle-password").change(function() {
  $(".password").attr("type", this.checked ? "text" : "password")
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" class="password">
<input type="password" class="password">
<input type="checkbox" class="toggle-password"> Show password


问:
VBS - File Created But I Can't See It Or Open It
I was trying to build a VBS to test creating files because a larger script I wrote isn't creating an output file. The point of the following script is to test functionality; which I'm not currently seeing.

```<code>Option Explicit
Dim objFSO, objFSOText, objFolder, objFile
Dim strDirectory, strFile
strDirectory = "C:\Test\next"
strFile = "\Try.txt"

' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Create the Folder specified by strDirectory on line 10
Set objFolder = objFSO.CreateFolder(strDirectory)

' -- The heart of the create file script
'-----------------------
'Creates the file using the value of strFile on Line 11
' -----------------------------------------------
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
Wscript.Echo "Just created " & strDirectory & strFile

Wscript.Quit
</code>```

While running this code, everything works the first time but there isn't an output file in the destination directory. When I run it again it throws an error that the file already exists.

答:
I think the problem is that you are trying to create the path "C:\Test\next", which is a structure of two nested folders) in one go and also do not test if that path already exists.

To create a nested folder structure, I have added a small helper function CreateNestedFolder to your code and tidied it up a bit:

```<code>Option Explicit

Dim strDirectory, strFile, overwrite

strDirectory = "C:\Test\next"
strFile      = "Try.txt"
overwrite    = True  'set this to False if you do not wish to overwrite an existing file

'Create the (nested) Folder Structure specified by strDirectory if it does not exist yet
If Not CreateNestedFolder(strDirectory) Then
    Wscript.Echo "Could not create folder " & strDirectory
Else
    Dim objFSO, objFile
    ' Create the File System Object
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    ' -- The heart of the create file script
    '-----------------------
    'Creates the file using the value of strFile
    ' -----------------------------------------------

    'combine the directory and filename
    strFile = strDirectory & "\" & strFile
    'Create the new file and write something in it
    Set objFile = objFSO.CreateTextFile(strFile, overwrite)
    objFile.WriteLine("This is a test.")
    objFile.Close
    Wscript.Echo "Just created " & strFile

    'Clean up the used objects
    Set objFile = Nothing
    Set objFSO  = Nothing
End If

Function CreateNestedFolder(ByVal sPath)
    'Helper function to create a nested folder structure.
    'Returns True on success, False otherwise
    Dim aFolders, oFso, i, firstIndex

    On Error Resume Next
    Set oFso = CreateObject("Scripting.FileSystemObject")

    'Check if the path already exists
    If Not oFso.FolderExists(sPath) Then
        'Find the root drive and split the path in subfolder parts
        aFolders = Split(sPath, "\")
        'Get the root path from the complete path
        If Left(sPath, 2) = "\\" Then
            'If this is a UNC path then the root will be "\\server\share"
            sPath = "\\" & aFolders(2) & "\" & aFolders(3)
            firstIndex = 4
        Else
            'For a local path, the root is "X:"
            aFolders = Split(sPath, "\")
            sPath = aFolders(0)
            firstIndex = 1
        End If
        'Loop through the aFolders array and create new folders if needed
        For i = firstIndex to UBound(aFolders)
            If Len(aFolders(i)) > 0 Then
                sPath = sPath & "\" & aFolders(i)
                If Not oFso.FolderExists(sPath) Then oFso.CreateFolder sPath
            End If
        Next
    End If

    CreateNestedFolder = (Err.Number = 0)
    On Error GoTo 0
    Set oFso = Nothing
End Function
</code>```

Body:
I was trying to build a VBS to test creating files because a larger script I wrote isn't creating an output file. The point of the following script is to test functionality; which I'm not currently seeing.

Option Explicit
Dim objFSO, objFSOText, objFolder, objFile
Dim strDirectory, strFile
strDirectory = "C:\Test\next"
strFile = "\Try.txt"

' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Create the Folder specified by strDirectory on line 10
Set objFolder = objFSO.CreateFolder(strDirectory)

' -- The heart of the create file script
'-----------------------
'Creates the file using the value of strFile on Line 11
' -----------------------------------------------
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
Wscript.Echo "Just created " & strDirectory & strFile

Wscript.Quit

While running this code, everything works the first time but there isn't an output file in the destination directory. When I run it again it throws an error that the file already exists.

Body:
I think the problem is that you are trying to create the path "C:\Test\next", which is a structure of two nested folders) in one go and also do not test if that path already exists.

To create a nested folder structure, I have added a small helper function CreateNestedFolder to your code and tidied it up a bit:

Option Explicit

Dim strDirectory, strFile, overwrite

strDirectory = "C:\Test\next"
strFile      = "Try.txt"
overwrite    = True  'set this to False if you do not wish to overwrite an existing file

'Create the (nested) Folder Structure specified by strDirectory if it does not exist yet
If Not CreateNestedFolder(strDirectory) Then
    Wscript.Echo "Could not create folder " & strDirectory
Else
    Dim objFSO, objFile
    ' Create the File System Object
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    ' -- The heart of the create file script
    '-----------------------
    'Creates the file using the value of strFile
    ' -----------------------------------------------

    'combine the directory and filename
    strFile = strDirectory & "\" & strFile
    'Create the new file and write something in it
    Set objFile = objFSO.CreateTextFile(strFile, overwrite)
    objFile.WriteLine("This is a test.")
    objFile.Close
    Wscript.Echo "Just created " & strFile

    'Clean up the used objects
    Set objFile = Nothing
    Set objFSO  = Nothing
End If

Function CreateNestedFolder(ByVal sPath)
    'Helper function to create a nested folder structure.
    'Returns True on success, False otherwise
    Dim aFolders, oFso, i, firstIndex

    On Error Resume Next
    Set oFso = CreateObject("Scripting.FileSystemObject")

    'Check if the path already exists
    If Not oFso.FolderExists(sPath) Then
        'Find the root drive and split the path in subfolder parts
        aFolders = Split(sPath, "\")
        'Get the root path from the complete path
        If Left(sPath, 2) = "\\" Then
            'If this is a UNC path then the root will be "\\server\share"
            sPath = "\\" & aFolders(2) & "\" & aFolders(3)
            firstIndex = 4
        Else
            'For a local path, the root is "X:"
            aFolders = Split(sPath, "\")
            sPath = aFolders(0)
            firstIndex = 1
        End If
        'Loop through the aFolders array and create new folders if needed
        For i = firstIndex to UBound(aFolders)
            If Len(aFolders(i)) > 0 Then
                sPath = sPath & "\" & aFolders(i)
                If Not oFso.FolderExists(sPath) Then oFso.CreateFolder sPath
            End If
        Next
    End If

    CreateNestedFolder = (Err.Number = 0)
    On Error GoTo 0
    Set oFso = Nothing
End Function


问:
Sphinx not rebuild on read only database
I am using master/slave databases for my app and have 2 slave , one for sphinx and one for users and as per rule 1 master

Slave databases are set read only. Issue is that when I rebuild sphinx on slave it gives an error

```<code>The MySQL server is running with the --read-only option so it cannot execute this statement
</code>```

How can I solve this issue?

答:
What I have done is that remove update delta query form thinking sphinx config by overriding class

```<code>class ReadOnlyDeltas < ThinkingSphinx::Deltas::DefaultDelta
  def reset_query
   nil
  end
end
</code>```

and extend models with this class

```<code>ThinkingSphinx::Index.define :table_name, :with => :active_record, :delta => ReadOnlyDeltas do
</code>```

Now what happend is that when I re_index or rebuild sphinx , it works fine on slave db also.

To update delta I write a script in ruby which update all deltas on master after 5 minutes using cronjob

Body:
I am using master/slave databases for my app and have 2 slave , one for sphinx and one for users and as per rule 1 master

Slave databases are set read only. Issue is that when I rebuild sphinx on slave it gives an error

The MySQL server is running with the --read-only option so it cannot execute this statement

How can I solve this issue?

Body:
What I have done is that remove update delta query form thinking sphinx config by overriding class

class ReadOnlyDeltas < ThinkingSphinx::Deltas::DefaultDelta
  def reset_query
   nil
  end
end

and extend models with this class

ThinkingSphinx::Index.define :table_name, :with => :active_record, :delta => ReadOnlyDeltas do

Now what happend is that when I re_index or rebuild sphinx , it works fine on slave db also.

To update delta I write a script in ruby which update all deltas on master after 5 minutes using cronjob


问:
Pull object as variable from PHP array (in Drupal 7 module)
Hopefully I'm asking this in a way that makes sense. Couldn't find anything out there that answered this, though I may not have been phrasing my search terms correctly.

In my Drupal 7 custom module I am able to get data out of a Taxonomy array successfully using the following object operator (arrow ->) syntax

```<code>$term = taxonomy_term_load($taxonomy_tid);
$description = $term->description;
echo $description;
</code>```

How can I make the "description" label itself a variable? The set up would be:

```<code>$term = taxonomy_term_load($taxonomy_tid);
$description_name_from_array = 'description';
$description = $term->????;
echo $description;
</code>```

Things that don't work:

$term->$description_name_from_array

$term->[$description_name_from_array]

$term->&$description_name_from_array

答:
Curly braces may be required in specific cases, but your 1st try should work for accessing description. The correct syntax for accessing a simple variable property from an object is

```<code> $obj->$property
</code>```

Class properties may also be accessed using variable property names.
  The variable property name will be resolved within the scope from
  which the call is made. For instance, if you have an expression such
  as $foo->$bar, then the local scope will be examined for $bar and its
  value will be used as the name of the property of $foo. This is also
  true if $bar is an array access.

It's safer though to encapsulate the variable with curly braces to clearly delimit the property name :

```<code>$obj->{$property}
</code>```

It is required when :

accessing values within a property that contains an array : $obj->${$properties[0]}

when the property name is made of multiple parts : $obj->{$a . $b}

when using a constant to access the property : $obj->{CONSTANT_NAME}

or when the property name contains characters that are not otherwise valid

See PHP's Variable Variables

Body:
Hopefully I'm asking this in a way that makes sense. Couldn't find anything out there that answered this, though I may not have been phrasing my search terms correctly.

In my Drupal 7 custom module I am able to get data out of a Taxonomy array successfully using the following object operator (arrow ->) syntax

$term = taxonomy_term_load($taxonomy_tid);
$description = $term->description;
echo $description;

How can I make the "description" label itself a variable? The set up would be:

$term = taxonomy_term_load($taxonomy_tid);
$description_name_from_array = 'description';
$description = $term->????;
echo $description;

Things that don't work:

$term->$description_name_from_array

$term->[$description_name_from_array]

$term->&$description_name_from_array

Body:
Curly braces may be required in specific cases, but your 1st try should work for accessing description. The correct syntax for accessing a simple variable property from an object is

 $obj->$property

Class properties may also be accessed using variable property names.
  The variable property name will be resolved within the scope from
  which the call is made. For instance, if you have an expression such
  as $foo->$bar, then the local scope will be examined for $bar and its
  value will be used as the name of the property of $foo. This is also
  true if $bar is an array access.

It's safer though to encapsulate the variable with curly braces to clearly delimit the property name :

$obj->{$property}

It is required when :

accessing values within a property that contains an array : $obj->${$properties[0]}

when the property name is made of multiple parts : $obj->{$a . $b}

when using a constant to access the property : $obj->{CONSTANT_NAME}

or when the property name contains characters that are not otherwise valid

See PHP's Variable Variables


问:
Add Event Method Is Adding Cell To Top, Not Bottom
I have the following method which is adding a cell to a tableview.  I want the added cell to be at the bottom, however right now it is adding it at the top.  Any suggestions?

addEvent method:

```<code>-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray insertObject:routine atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.routineTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
     }
</code>```

ViewDidLoad

```<code>- (void)viewDidLoad
{
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}
</code>```

答:
The specific answer to your question is that your table has an array as a datasource and you are adding a new item at the beginning of the array. Therefore, when the table is reloaded, the new cell is at the top.

For a deeper understanding, I recommend you understand the following topics at minimum:

common data types used as data sources with tables (arrays and dictionaries mainly)

how table views work (e.g. what is tableView.dataSource and tableView.delegate)

methods of reloading the table when the dataSource changes (what you did is ok but not always what you'll want)

ContentLicense: CC BY-SA 3.0

Body:
I have the following method which is adding a cell to a tableview.  I want the added cell to be at the bottom, however right now it is adding it at the top.  Any suggestions?

addEvent method:

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray insertObject:routine atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.routineTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
     }

ViewDidLoad

- (void)viewDidLoad
{
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}


问:
The command "npm run build -- --prod" exited with code 1 error
I'm developing an Asp.Net Core 2 and Angular 5 project in visual studio 2017.

When I'm going to publish my project then the error 'The command "npm run build -- --prod" exited with code 1' show in error list window.

I created the project with Angular CLI in ASP.NET Core 2 Angular template
 link and everything was fine and the project run and publish correctly.

After a while, I don't know what exactly happens that cause the project doesn't publish.

In the npm-debug.log file

```<code>0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'build',
1 verbose cli   '--',
1 verbose cli   '--prod' ]
2 info using npm@3.10.10
3 info using node@v6.10.3
4 verbose stack Error: ENOENT: no such file or directory, open 'C:\Project\JWS\JWSApplication\package.json'
4 verbose stack     at Error (native)
5 verbose cwd C:\Project\JWS\JWSApplication
6 error Windows_NT 10.0.15063
7 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "build" "--" "--prod"
8 error node v6.10.3
9 error npm  v3.10.10
10 error path C:\Project\JWS\JWSApplication\package.json
11 error code ENOENT
12 error errno -4058
13 error syscall open
14 error enoent ENOENT: no such file or directory, open 'C:\Project\JWS\JWSApplication\package.json'
15 error enoent ENOENT: no such file or directory, open 'C:\Project\JWS\JWSApplication\package.json'
15 error enoent This is most likely not a problem with npm itself
15 error enoent and is related to npm not being able to find a file.
16 verbose exit [ -4058, true ]
</code>```

答:
Check this maybe you have problem with lack of memory</p>

```<code> "build": "node --max-old-space-size=4069 node_modules/@angular/cli/bin/ng build --prod",
</code>```

Body:
I'm developing an Asp.Net Core 2 and Angular 5 project in visual studio 2017.

When I'm going to publish my project then the error 'The command "npm run build -- --prod" exited with code 1' show in error list window.

I created the project with Angular CLI in ASP.NET Core 2 Angular template
 link and everything was fine and the project run and publish correctly.

After a while, I don't know what exactly happens that cause the project doesn't publish.

In the npm-debug.log file

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'build',
1 verbose cli   '--',
1 verbose cli   '--prod' ]
2 info using npm@3.10.10
3 info using node@v6.10.3
4 verbose stack Error: ENOENT: no such file or directory, open 'C:\Project\JWS\JWSApplication\package.json'
4 verbose stack     at Error (native)
5 verbose cwd C:\Project\JWS\JWSApplication
6 error Windows_NT 10.0.15063
7 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "build" "--" "--prod"
8 error node v6.10.3
9 error npm  v3.10.10
10 error path C:\Project\JWS\JWSApplication\package.json
11 error code ENOENT
12 error errno -4058
13 error syscall open
14 error enoent ENOENT: no such file or directory, open 'C:\Project\JWS\JWSApplication\package.json'
15 error enoent ENOENT: no such file or directory, open 'C:\Project\JWS\JWSApplication\package.json'
15 error enoent This is most likely not a problem with npm itself
15 error enoent and is related to npm not being able to find a file.
16 verbose exit [ -4058, true ]

Body:
Check this maybe you have problem with lack of memory

 "build": "node --max-old-space-size=4069 node_modules/@angular/cli/bin/ng build --prod",


问:
How to merge two arrays (song&title) into one multidimensional array?
I have two arrays:

```<code>Array
(
 [0] => Black
 [1] => Five Hours
 [2] => Bvulgari
 [3] => Imaginary
)

Array
(
 [0] => Pearl Jam
 [1] => Deorro
 [2] => Daddy's Groove
 [3] => Brennan Heart
)
</code>```

I want to be able to achieve the following:
I want to have the song title and the Artist into one 'dimension' of the array,
This is how I want it to be:

```<code>Array
(
     [0] => Array
            (
              [0] => Black
              [1] => Pearl Jam
            )
     [1] => Array
            (
              [0] => Five Hours
              [1] => Deorro
            )
     [2] => Array
            (
              [0] => Bvulgari
              [1] => Daddy's Groove

            )
     [3] => Array
            (
              [0] => Imaginary
              [1] => Brennan Heart
            )

)
</code>```

The two arrays that are the input can change depending on the requestor's input.

答:
As an alternative you could use array_map and use both array's:

```<code>$result = array_map(function ($s, $a) {
    return [$s, $a];
}, $songs, $artists);

print_r($result);
</code>```

See a Php demo

Result

```<code>Array
(
    [0] => Array
        (
            [0] => Black
            [1] => Pearl Jam
        )

    [1] => Array
        (
            [0] => Five Hours
            [1] => Deorro
        )

    [2] => Array
        (
            [0] => Bvulgari
            [1] => Daddy's Groove
        )

    [3] => Array
        (
            [0] => Imaginary
            [1] => Brennan Heart
        )

)
</code>```

Body:
I have two arrays:

Array
(
 [0] => Black
 [1] => Five Hours
 [2] => Bvulgari
 [3] => Imaginary
)

Array
(
 [0] => Pearl Jam
 [1] => Deorro
 [2] => Daddy's Groove
 [3] => Brennan Heart
)

I want to be able to achieve the following:
I want to have the song title and the Artist into one 'dimension' of the array,
This is how I want it to be:

Array
(
     [0] => Array
            (
              [0] => Black
              [1] => Pearl Jam
            )
     [1] => Array
            (
              [0] => Five Hours
              [1] => Deorro
            )
     [2] => Array
            (
              [0] => Bvulgari
              [1] => Daddy's Groove

            )
     [3] => Array
            (
              [0] => Imaginary
              [1] => Brennan Heart
            )

)

The two arrays that are the input can change depending on the requestor's input.

Body:
As an alternative you could use array_map and use both array's:

$result = array_map(function ($s, $a) {
    return [$s, $a];
}, $songs, $artists);

print_r($result);

See a Php demo

Result

Array
(
    [0] => Array
        (
            [0] => Black
            [1] => Pearl Jam
        )

    [1] => Array
        (
            [0] => Five Hours
            [1] => Deorro
        )

    [2] => Array
        (
            [0] => Bvulgari
            [1] => Daddy's Groove
        )

    [3] => Array
        (
            [0] => Imaginary
            [1] => Brennan Heart
        )

)


问:
How to get the custom post type id
I have a product page which is a custom post type, now i want the category id of that specific page and place it in the post loop. And create a slick slider with it.

this is what i came up with.

single-product page

```<code><section class="product">
    <div class="productslider">
        <?php
        global $post;
        $Taxonomy = get_object_taxonomies('producten');

        if (count($Taxonomy) > 0) {
            foreach ($Taxonomy as $tax) {
                $args = array(
                    'taxonomy' => $tax,
                );

                $cats = get_categories($args);

                $cats = $cats[0]->term_id;
            }
        }

        $args = array('posts_per_page' => 5, 'post_type' => 'producten', 'category' =>  $cats);

        $posts = get_posts($args);
        if ($posts) :
            foreach ($posts as $post) :
                setup_postdata($post); ?>
                <div class="productslider__slide">
                    <?php echo get_the_post_thumbnail(); ?>
                    <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
                </div>

            <?php endforeach;
        wp_reset_postdata();
    endif; ?>
    </div>
</section>
</code>```

slick

```<code>$('.productslider').slick({
    slidesToShow: 3,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 2000,
    arrows: false,
    dots: true,
    centerMode: true,
});
</code>```

is this a good solution?
it seems like i am getting the same ids on every page

答:
How i solved it using Manan Vyas answer</p>

```<code>$Taxonomy = get_object_taxonomies('producten');
   if (count($Taxonomy) > 0) {
      foreach ($Taxonomy as $tax) {
         $args = array(
            'taxonomy' => $tax,
         );

         $cat_array = array();
         $cats = get_categories($args);

         foreach($cats as $data) {
            array_push($cat_array, $data->term_id);
         }
      }
   }

$args = array('posts_per_page' => 5, 'post_type' => 'producten', 'category' =>  $cat_array);
</code>```

Title: How to get the custom post type id

Body:
I have a product page which is a custom post type, now i want the category id of that specific page and place it in the post loop. And create a slick slider with it.

this is what i came up with.

single-product page

        <?php
        global $post;
        $Taxonomy = get_object_taxonomies('producten');

        if (count($Taxonomy) > 0) {
            foreach ($Taxonomy as $tax) {
                $args = array(
                    'taxonomy' => $tax,
                );

                $cats = get_categories($args);

                $cats = $cats[0]->term_id;
            }
        }

        $args = array('posts_per_page' => 5, 'post_type' => 'producten', 'category' =>  $cats);

        $posts = get_posts($args);
        if ($posts) :
            foreach ($posts as $post) :
                setup_postdata($post); ?>

                    <?php echo get_the_post_thumbnail(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

            <?php endforeach;
        wp_reset_postdata();
    endif; ?>

slick

$('.productslider').slick({
    slidesToShow: 3,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 2000,
    arrows: false,
    dots: true,
    centerMode: true,
});

is this a good solution?
it seems like i am getting the same ids on every page

Body:
How i solved it using Manan Vyas answer

$Taxonomy = get_object_taxonomies('producten');
   if (count($Taxonomy) > 0) {
      foreach ($Taxonomy as $tax) {
         $args = array(
            'taxonomy' => $tax,
         );

         $cat_array = array();
         $cats = get_categories($args);

         foreach($cats as $data) {
            array_push($cat_array, $data->term_id);
         }
      }
   }

$args = array('posts_per_page' => 5, 'post_type' => 'producten', 'category' =>  $cat_array);


问:
When a page delivers secure and non-secure items over https, are the secure items compromised?
I'm not 100% sure that I'm using the correct terminology or if I'm leaving out information that is required to answer. So please be patient with me.

My client wants to include a video feed from an outside source inside a members area of their website. The members area is delivered over https and the video feed is not. Does this compromise the secure data?

I know that some browsers alert the user that there are secure and non-secure data being loaded on the page. Frankly, my client is okay with that, but I don't want to move forward if the user account information (specifically, session, etc.) is compromised.

Thanks for any help.

答:
If you identify your user based on a cookie, e.g. using a standard SessionId, then you are vulnerable, even if only referencing static images.

By default, the user's browser will resend the session cookie for each request to the same host, irrelevant of protocol. I.e. you securely authenticated your user using HTTPS on your login form, and ensure to continue using HTTPS for all sensitive pages...

However, you also include "non-sensitive" images over HTTP... the user's browser will happily send the sensitive session cookie over non-encrypted, non-secure, plain-text HTTP, when requesting those images.

Then it's just a matter of grabbing that cookie from HTTP, and impersonating your users back on the secure part of the site.

Note, this is by default.
You CAN change this behavior, by adding the secure; attribute to your cookies. Depending on your framework, you can configure it to happen automatically. Again, this is not the default, you have to explicitly change it.

And while you're at it, add the httpOnly; attribute too.


问:
How can I test if a class method is calling another method from one of the classes's private objects
I'm trying to create Unit tests for a project. In my project I have a Menu Class, and a VerticalOptions Class.

My menu class has a private VerticalOptions object and a public handleInput method.
When I call my menu's handleInput(key) method, depending on the key I give it it'll do different things, namely call different methods of my VerticalOptions object.

I want to make a unitTest to see if the methods being called are the correct ones, how can I do that?

I've tried adding a Mockito spy to my menu, however since I want to test if the method being called was the method in the private VerticalOptions object, it doesn't really work.

I've also tried putting the spy on the VerticalOptions object, after getting it with a getVerticalOptions method, but it also doesn't work.

```<code>public void handleInput(InputKey key)
{
    switch (key) {
        case S:
        case DOWN:
            optionsInterface.cycleDown();
            break;
        case W:
        case UP:
            optionsInterface.cycleUp();
            break;
        case SPACE:
        case ENTER:
            optionsInterface.select();
            break;
        default:
            break;
    }
}

@Test
public void testInput() {
    MainMenu menu = new MainMenu(game);
    VerticalButtonInterface buttonInterface = menu.getOptionsInterface();
    VerticalButtonInterface spy = spy(buttonInterface);

    menu.handleInput(InputKey.DOWN);
    verify(spy, times(1)).cycleDown();
}
</code>```

This is the test failure I got:

Wanted but not invoked:
verticalButtonInterface.cycleDown();
-> at MenuTest.testInput(MenuTest.java:60)
Actually, there were zero interactions with this mock.

答:
I will give you an alternative view on this. I have seen a lot of people going down the wrong path and when you do that, everything else becomes hard to do / test, which is exactly what you are doing now.

Start here, what are you trying to achieve?

I want to test and make sure that a certain method is called ...

Is this a good thing? What is a unit test not meant to have? That is deep knowledge of the code.

Why? Because every time you make slight changes to the code, you'll have to change the test because of this deep knowledge. if you have 1000 tests, you're in for a hard road.

Ok, so we now know what the problem is, so how do we solve it? Well, first let's make sure we can have a test without deep knowledge of the code.

How do we do that? Well, imagine that your code adds an extra step, a flag which sets a state. You might have a flag which stores a resulting state ...

you have 3 methods you want to call, so you will need 3 different states, so create a variable which reflects that, be it a string, or an enum or whatever else makes you happy.

For example sake, let's say we create a string with 3 possible values: cycleDown, cycleUp and select.

your code starts to look something like :

```<code>public string handleInput(InputKey key)
{
      String state = determineState(key);
      SomeType someResult = executeActionForState(state);
}

public String determineState(string key)
{

    String state = "";
     switch (key) {
    case S:
    case DOWN:
        state = "cycleDown";
        break;
    case W:
    case UP:
        state = "cycleUp";
        break;
    case SPACE:
    case ENTER:
        state = "select";
        break;
    default:
        break;
}

return state;
}

public void executeActionForState(string state)
{
     if ( state == "cycleup" ) {
     }

     etc etc
}
</code>```

Now, I may not necessarily code your example like this, this is a bit forced, it depends on what other things you're doing with the code, but this is meant to show how you separate functionality from UI aspects.

I can easily test the state method, I can change its code and I wouldn't have to change the test, because the test would look at the inputs and outputs and not how things are achieved.

Unit testing is about functionality, it's about having simple tests that don't need to change once created. Verifying that a method has been called doesn't give you anything worthwhile, because you don't know what that method does later.

UI stuff you can test in other ways, unit testing is only about correct functionality. If you do not make this separation clear then you will have trouble maintaining your tests, it will become harder and harder until you give up.

You would test that you get the correct state, then you test that cycleUp method does something correct based on your requirements and that's how you know each part works in isolation. Later on you start looking at integration tests, Automated UI tests, but those are different things. Keep unit testing for what it's meant to do, keep it simple, keep it not tied to other code and then everything becomes simple. You won't need to mock much, you won't need to worry too much about complex setups and you won't need to change your tests every time something in the code changes.

Now, to address the final part of the question, private methods, you test them by observing their outputs. You must have something public in your class that changes when a private method is called. So test that.

Body:
I'm trying to create Unit tests for a project. In my project I have a Menu Class, and a VerticalOptions Class.

My menu class has a private VerticalOptions object and a public handleInput method.
When I call my menu's handleInput(key) method, depending on the key I give it it'll do different things, namely call different methods of my VerticalOptions object.

I want to make a unitTest to see if the methods being called are the correct ones, how can I do that?

I've tried adding a Mockito spy to my menu, however since I want to test if the method being called was the method in the private VerticalOptions object, it doesn't really work.

I've also tried putting the spy on the VerticalOptions object, after getting it with a getVerticalOptions method, but it also doesn't work.

public void handleInput(InputKey key)
{
    switch (key) {
        case S:
        case DOWN:
            optionsInterface.cycleDown();
            break;
        case W:
        case UP:
            optionsInterface.cycleUp();
            break;
        case SPACE:
        case ENTER:
            optionsInterface.select();
            break;
        default:
            break;
    }
}

@Test
public void testInput() {
    MainMenu menu = new MainMenu(game);
    VerticalButtonInterface buttonInterface = menu.getOptionsInterface();
    VerticalButtonInterface spy = spy(buttonInterface);

    menu.handleInput(InputKey.DOWN);
    verify(spy, times(1)).cycleDown();
}

This is the test failure I got:

Wanted but not invoked:
verticalButtonInterface.cycleDown();
-> at MenuTest.testInput(MenuTest.java:60)
Actually, there were zero interactions with this mock.

Body:
I will give you an alternative view on this. I have seen a lot of people going down the wrong path and when you do that, everything else becomes hard to do / test, which is exactly what you are doing now.

Start here, what are you trying to achieve?

I want to test and make sure that a certain method is called ...

Is this a good thing? What is a unit test not meant to have? That is deep knowledge of the code.

Why? Because every time you make slight changes to the code, you'll have to change the test because of this deep knowledge. if you have 1000 tests, you're in for a hard road.

Ok, so we now know what the problem is, so how do we solve it? Well, first let's make sure we can have a test without deep knowledge of the code.

How do we do that? Well, imagine that your code adds an extra step, a flag which sets a state. You might have a flag which stores a resulting state ...

you have 3 methods you want to call, so you will need 3 different states, so create a variable which reflects that, be it a string, or an enum or whatever else makes you happy.

For example sake, let's say we create a string with 3 possible values: cycleDown, cycleUp and select.

your code starts to look something like :

public string handleInput(InputKey key)
{
      String state = determineState(key);
      SomeType someResult = executeActionForState(state);
}

public String determineState(string key)
{

    String state = "";
     switch (key) {
    case S:
    case DOWN:
        state = "cycleDown";
        break;
    case W:
    case UP:
        state = "cycleUp";
        break;
    case SPACE:
    case ENTER:
        state = "select";
        break;
    default:
        break;
}

return state;
}

public void executeActionForState(string state)
{
     if ( state == "cycleup" ) {
     }

     etc etc
}

Now, I may not necessarily code your example like this, this is a bit forced, it depends on what other things you're doing with the code, but this is meant to show how you separate functionality from UI aspects.

I can easily test the state method, I can change its code and I wouldn't have to change the test, because the test would look at the inputs and outputs and not how things are achieved.

Unit testing is about functionality, it's about having simple tests that don't need to change once created. Verifying that a method has been called doesn't give you anything worthwhile, because you don't know what that method does later.

UI stuff you can test in other ways, unit testing is only about correct functionality. If you do not make this separation clear then you will have trouble maintaining your tests, it will become harder and harder until you give up.

You would test that you get the correct state, then you test that cycleUp method does something correct based on your requirements and that's how you know each part works in isolation. Later on you start looking at integration tests, Automated UI tests, but those are different things. Keep unit testing for what it's meant to do, keep it simple, keep it not tied to other code and then everything becomes simple. You won't need to mock much, you won't need to worry too much about complex setups and you won't need to change your tests every time something in the code changes.

Now, to address the final part of the question, private methods, you test them by observing their outputs. You must have something public in your class that changes when a private method is called. So test that.


问:
Difference between current week of year and previous weeks
I have a SQL query which calculated the difference between the current weekday and previous weekdays in terms of weeks and I need to translate this to DAX query.

SQL :

```<code>DATEDIFF(Week,Getdate(),
      DATEADD (WEEK, CAST (RIGHT(CAST ([Code] AS nvarchar),2) AS int),
      DATEADD (YEAR, ([Code] / 100)-1900, 0)) - 4 -
      DATEPART(dw,
                 DATEADD (WEEK, CAST (RIGHT(CAST ([Code] AS nvarchar),2) AS int),
       DATEADD (YEAR, ([Code] / 100)-1900, 0)) - 4) + 1)

 AS [WeekIndex]

enter code here
</code>```

Expected Result: If code = 201821 then WeekIndex has to be -53 as the current week is week 22

答:
I think you are looking for something like this:

```<code>[Measure] :=
    VAR code = "201821"
    VAR code_year = LEFT ( code, 4 )
    VAR code_week = RIGHT ( code, 2 )
    VAR code_date = DATE ( code_year, 1, -2 ) - WEEKDAY ( DATE ( code_year, 1, 3 ) )
        + code_week * 7
RETURN
    DATEDIFF ( TODAY (), code_date, WEEK )
</code>```

VAR [code_date] will return the monday of the given VAR [code] as a datevalue

Body:
I have a SQL query which calculated the difference between the current weekday and previous weekdays in terms of weeks and I need to translate this to DAX query.

SQL :

DATEDIFF(Week,Getdate(),
      DATEADD (WEEK, CAST (RIGHT(CAST ([Code] AS nvarchar),2) AS int),
      DATEADD (YEAR, ([Code] / 100)-1900, 0)) - 4 -
      DATEPART(dw,
                 DATEADD (WEEK, CAST (RIGHT(CAST ([Code] AS nvarchar),2) AS int),
       DATEADD (YEAR, ([Code] / 100)-1900, 0)) - 4) + 1)

 AS [WeekIndex]

enter code here

Expected Result: If code = 201821 then WeekIndex has to be -53 as the current week is week 22

Body:
I think you are looking for something like this:

[Measure] :=
    VAR code = "201821"
    VAR code_year = LEFT ( code, 4 )
    VAR code_week = RIGHT ( code, 2 )
    VAR code_date = DATE ( code_year, 1, -2 ) - WEEKDAY ( DATE ( code_year, 1, 3 ) )
        + code_week * 7
RETURN
    DATEDIFF ( TODAY (), code_date, WEEK )

VAR [code_date] will return the monday of the given VAR [code] as a datevalue


问:
Non English characters in ggplot within a knitr document
I'm trying to knit to pdf a file with Lithuanian characters like ąčęėįšųž in RStudio from .Rmd file. While knitting to html works properly and the ggplot title has the Lithuanian characters, when knitting to pdf ggplot does create warnings and dismisses these characters.

Reproducible example:

```<code>---
title: "Untitled"
output:
  pdf_document:
    includes:
      in_header: header_lt_text.txt
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
```

## Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž
```{r}
ggplot(iris, aes(Sepal.Length, Sepal.Width))+
    geom_point(aes(col=Species))+
    labs(title="Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž")

```
</code>```

I pass the header_lt_text.txt with follwoing arguments:

```<code>\usepackage[utf8]{inputenc}
\usepackage[L7x]{fontenc}
\usepackage[lithuanian]{babel}

\usepackage{setspace}
\onehalfspacing
</code>```

Any suggestions on how to make ggplot create correct labels?

答:
The problem is with the pdf device and is only apparent when saving the picture as pdf (which you want because it looks much, much better). This is why it seems to "work" in some cases: the image is not rendered as pdf but e.g. as png. Thanks to @Konrad for correctly identifying the source of the problem.

To solve this, you need to pass the correct encoding to the pdf device.
Fortunately, the pdf device (?pdf) takes an encoding argument and there is a chunk option to pass arguments to the device: dev.args

On Windows, an appropriate encoding is CP1257.enc (Baltic):

```<code>```{r dev="pdf", dev.args=list(encoding="CP1257.enc")}
  ggplot(iris, aes(Sepal.Length, Sepal.Width))+
  geom_point(aes(col=Species))+
  labs(title="Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž")
```
</code>```

You can see the other encodings available out of the box with: list.files(system.file("enc", package = "grDevices"))

Works well on my linux machine:

Alternatively, if you're happy to get png images inserted in the pdf, you can simply use dev="png" in your chunk option. Doesn't look as good though.

Body:
I'm trying to knit to pdf a file with Lithuanian characters like ąčęėįšųž in RStudio from .Rmd file. While knitting to html works properly and the ggplot title has the Lithuanian characters, when knitting to pdf ggplot does create warnings and dismisses these characters.

Reproducible example:

---
title: "Untitled"
output:
  pdf_document:
    includes:
      in_header: header_lt_text.txt
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
```

## Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž
```{r}
ggplot(iris, aes(Sepal.Length, Sepal.Width))+
    geom_point(aes(col=Species))+
    labs(title="Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž")

```

I pass the header_lt_text.txt with follwoing arguments:

\usepackage[utf8]{inputenc}
\usepackage[L7x]{fontenc}
\usepackage[lithuanian]{babel}

\usepackage{setspace}
\onehalfspacing

Any suggestions on how to make ggplot create correct labels?

Body:
The problem is with the pdf device and is only apparent when saving the picture as pdf (which you want because it looks much, much better). This is why it seems to "work" in some cases: the image is not rendered as pdf but e.g. as png. Thanks to @Konrad for correctly identifying the source of the problem.

To solve this, you need to pass the correct encoding to the pdf device.
Fortunately, the pdf device (?pdf) takes an encoding argument and there is a chunk option to pass arguments to the device: dev.args

On Windows, an appropriate encoding is CP1257.enc (Baltic):

```{r dev="pdf", dev.args=list(encoding="CP1257.enc")}
  ggplot(iris, aes(Sepal.Length, Sepal.Width))+
  geom_point(aes(col=Species))+
  labs(title="Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž")
```

You can see the other encodings available out of the box with: list.files(system.file("enc", package = "grDevices"))

Works well on my linux machine:

Alternatively, if you're happy to get png images inserted in the pdf, you can simply use dev="png" in your chunk option. Doesn't look as good though.


问:
How can i feature extraction (.wav) form folders and sub-folders for using as input of the neural network?
This is my code, please help me to correct:

```<code>from pathlib import Path
from python_speech_features import fbank
import scipy.io.wavfile as wavfile

path = Path('/home/narges/dataset/seri1.16khz.128kbps/Voice   Recorder/N00xxxx/').glob('*/*.wav')
wavs = [str(wavf) for wavf in path if wavf.is_file()]
wavs.sort()

print(wavs)

number_of_files=len(wavs)

wav_data=[]

for i in range(number_of_files):
    samplerate, data=wavfile.read(wavs[i])
    wav_data.append(data)
print(wav_data)

fbank_feat=fbank(samplerate, data)
print(fbank_feat)
</code>```

my error is: 'int' object is not subscriptable. How can i correct this?

答:
Finally i used this code and it's correct:</p>

```<code>from pathlib import Path
from python_speech_features import fbank
import scipy.io.wavfile as wavfile
import numpy as np

path = Path('/home/narges/dataset/seri1.16khz.128kbps/Voice Recorder/N00xxxx/').glob('*/*.wav')
wavs = [str(wavf) for wavf in path if wavf.is_file()]
wavs.sort()
print(wavs)

number_of_files=len(wavs)

for i in range(number_of_files):
    (rate, sig) = wavfile.read(wavs[i])

fbank_feat=fbank(sig, rate, winlen=0.06, winstep=0.01, nfilt=26, nfft=512, lowfreq=0, highfreq=rate/2, preemph=0.97, winfunc=np.hamming)
print(fbank_feat)
</code>```

Body:
This is my code, please help me to correct:

from pathlib import Path
from python_speech_features import fbank
import scipy.io.wavfile as wavfile

path = Path('/home/narges/dataset/seri1.16khz.128kbps/Voice   Recorder/N00xxxx/').glob('*/*.wav')
wavs = [str(wavf) for wavf in path if wavf.is_file()]
wavs.sort()

print(wavs)

number_of_files=len(wavs)

wav_data=[]

for i in range(number_of_files):
    samplerate, data=wavfile.read(wavs[i])
    wav_data.append(data)
print(wav_data)

fbank_feat=fbank(samplerate, data)
print(fbank_feat)

my error is: 'int' object is not subscriptable. How can i correct this?

Body:
Finally i used this code and it's correct:

from pathlib import Path
from python_speech_features import fbank
import scipy.io.wavfile as wavfile
import numpy as np

path = Path('/home/narges/dataset/seri1.16khz.128kbps/Voice Recorder/N00xxxx/').glob('*/*.wav')
wavs = [str(wavf) for wavf in path if wavf.is_file()]
wavs.sort()
print(wavs)

number_of_files=len(wavs)

for i in range(number_of_files):
    (rate, sig) = wavfile.read(wavs[i])

fbank_feat=fbank(sig, rate, winlen=0.06, winstep=0.01, nfilt=26, nfft=512, lowfreq=0, highfreq=rate/2, preemph=0.97, winfunc=np.hamming)
print(fbank_feat)