text:
Q: How to change the icon of an external EXE file using Delphi? I want to change a formerly generated EXE file's main icon using Delphi. The EXE file was also generated by me using Delphi. But I want the user to be able to change its icon.
I tried using UpdateResource function to change RT_GROUP_ICON and RT_ICON without success:
procedure UpdateExeIcon(Const IconFilename, ExternalExeFilename:string);
var
  Stream     : TFileStream;
  hDestRes   : THANDLE;
  lpData     : Pointer;
  cbData     : DWORD;
begin
  Stream := TFileStream.Create(IconFilename,fmOpenRead or fmShareDenyNone);
  try
    Stream.Seek(0, soFromBeginning);
    cbData:=Stream.Size;
    if cbData>0 then
    begin
      GetMem(lpData,cbData);
      try
        Stream.Read(lpData^, cbData);
        hDestRes:= BeginUpdateResource(PChar(ExternalExeFilename), False);
        if hDestRes <> 0 then
        begin
          //if UpdateResource(hDestRes, RT_ICON,PChar('1'),1033,lpData,cbData) then
          if UpdateResource(hDestRes, RT_GROUP_ICON,PChar('MAINICON'),1033,lpData,cbData) then
          begin
            if not EndUpdateResource(hDestRes,FALSE) then RaiseLastOSError;
          end else RaiseLastOSError;
        end else RaiseLastOSError;
      finally
        FreeMem(lpData);
      end;
    end;
  finally
    Stream.Free;
  end;
end;

A: There are multiple mistakes:

*

*In UpdateResource(hDestRes, RT_ICON,PChar('1'),1033,lpData,cbData) the lpName parameter works in two ways: PChar('1') will turn out as a text, while MakeIntResource(1) will turn out as a number. You want the latter variant, not the former.

*For the resource type RT_ICON you have to provide the actual Icon payload, not an entire Icon file. Right now you do the latter, not the former. Look at how an Icon file looks like, then look at what the resource only has.

*The resource type RT_GROUP_ICON is "only" an index describing existing RT_ICON resources and should be patched as per your updated Icon (unless width, height, colors, pixel depth and payload length are all the same). Filling in file contents here makes never sense.

Above you see Resource Hacker displaying the raw bytes of the resource we want to update. 128 is the length of bytes in hexadecimal.

Above you see HxD displaying a whole Icon file - I selected the part where the first icon payload resides: starting at offset 26 with a length of 128 (both hexadecimal). Both byte sequences match.
If you do all that (using MakeIntResource(1) on RT_ICON and provide only the picture data of the Icon file) then you're fine - it worked for me fine: my EXE then displayed the new icon in Windows' Explorer (haven't executed it, tho). Updating the RT_GROUP_ICON should also be done, since I'm not sure up to where it seems to have no effect and when it suddenly becomes a problem. Viewing your files in a hex editor and your EXE in a resource editor will make you understand much better all the actions. Further reading:

*

*The Icon file format (quite easy)

*The RT_GROUP_ICON format (almost identical to Icon files)


text:
Q: Generate a dynamic query in java using string builder I am trying to generate a dynamic query in java, I need to generate the same table Cos_Class_Allocation and also the same columns  class_name = ? AND CLASS_ALLOCATION = ?. How can I clean my code in the loops I notice I declare alloc but did not called it, is there a better way to write the loops and also how can I remove the last comma from my first foreach loop and finally remove the last "And " from the second foreach loop.
My Query should look like this:
SELECT * FROM TRAFFIC_PROFILE
         WHERE COS_MODEL = 'cos4' AND DIRECTION = 'Egress'

          AND (PE_INGRESS_FLAG = 'Y' OR PE_EGRESS_FLAG = 'Y')

         and TRAFFIC_PROFILE_ID IN (

         select distinct (C1.Traffic_PROFILE_ID) from Cos_Class_Allocation C1,
         Cos_Class_Allocation C2, Cos_Class_Allocation C3,
         Cos_Class_Allocation C4, Cos_Class_Allocation C5, Cos_Class_Allocation C6
         where c1.class_name = ? AND c1.CLASS_ALLOCATION = ?
         and c2.class_name = ? AND c2.CLASS_ALLOCATION = ?
         and c3.class_name = ? AND c3.CLASS_ALLOCATION = ?
         and c4.class_name = ? AND c4.CLASS_ALLOCATION = ?
         and c5.class_name = ? AND c5.CLASS_ALLOCATION = ?
         and c6.class_name = ? AND c6.CLASS_ALLOCATION = ?
         and C1.TRAFFIC_PROFILE_ID = c2.TRAFFIC_PROFILE_ID
         and C1.TRAFFIC_PROFILE_ID = c3.TRAFFIC_PROFILE_ID
         and C1.TRAFFIC_PROFILE_ID = c4.TRAFFIC_PROFILE_ID
         and C1.TRAFFIC_PROFILE_ID = c5.TRAFFIC_PROFILE_ID
         and C1.TRAFFIC_PROFILE_ID = c6.TRAFFIC_PROFILE_ID ) ;

code:
private String buildTrafficProfileByCosClassAllocationQuery(TrafficProfileExtension.CosModel cosModel, Direction direction, List<ClassOfServiceAllocation> cosAllocation, RouterType routerType){
    StringBuilder builder = new StringBuilder();

    builder.append(queryByDirectionRouterTypeAndCosClassAllocation);
    builder.append(buildRouterQuery(routerType));
    builder.append("and TRAFFIC_PROFILE_ID IN ( select distinct (C1.Traffic_PROFILE_ID) from ");
//  builder.append(buildCosModelQuery(cosModel));

    int i = 1;

    for(ClassOfServiceAllocation alloc : cosAllocation){
        builder.append(" Cos_Class_Allocation c" + i++ +"," );

    }
    builder.append(" where "  );
    int n = 1;
    int a =1;

    for(ClassOfServiceAllocation alloc : cosAllocation){
    builder.append("c" + n++ + ".class_name = ? AND c" + a++ + ".CLASS_ALLOCATION = ? AND ");

    }

    int tp = 2;
    for(ClassOfServiceAllocation alloc : cosAllocation){
        builder.append("and C1.TRAFFIC_PROFILE_ID = c" + tp++ + ".TRAFFIC_PROFILE_ID " );
    }

    return builder.toString();
}

this is the output below: (I have an extra AND and extra after last table comma )
SELECT * FROM TRAFFIC_PROFILE
WHERE COS_MODEL = ? AND DIRECTION = ?
AND (PE_INGRESS_FLAG = 'Y' OR PE_EGRESS_FLAG = 'Y')
and TRAFFIC_PROFILE_ID IN (
select distinct (C1.Traffic_PROFILE_ID)
from  Cos_Class_Allocation c1, Cos_Class_Allocation c2,
Cos_Class_Allocation c3, Cos_Class_Allocation c4,
Cos_Class_Allocation c5, Cos_Class_Allocation c6,
where c1.class_name = ? AND c1.CLASS_ALLOCATION = ?
AND c2.class_name = ? AND c2.CLASS_ALLOCATION = ?
AND c3.class_name = ? AND c3.CLASS_ALLOCATION = ?
AND c4.class_name = ? AND c4.CLASS_ALLOCATION = ?
AND c5.class_name = ? AND c5.CLASS_ALLOCATION = ?
AND c6.class_name = ? AND c6.CLASS_ALLOCATION = ?
AND and C1.TRAFFIC_PROFILE_ID = c2.TRAFFIC_PROFILE_ID
and C1.TRAFFIC_PROFILE_ID = c3.TRAFFIC_PROFILE_ID
and C1.TRAFFIC_PROFILE_ID = c4.TRAFFIC_PROFILE_ID
and C1.TRAFFIC_PROFILE_ID = c5.TRAFFIC_PROFILE_ID
and C1.TRAFFIC_PROFILE_ID = c6.TRAFFIC_PROFILE_ID

A: I was able to generate my dynamic query by using for loop instead of a foreach loop.
private String buildTrafficProfileByCosClassAllocationQuery(TrafficProfileExtension.CosModel cosModel, Direction direction, List<ClassOfServiceAllocation> cosAllocation, RouterType routerType){
    StringBuilder builder = new StringBuilder();

    builder.append(queryByDirectionRouterTypeAndCosClassAllocation);
    builder.append(buildRouterQuery(routerType));
    builder.append("and TRAFFIC_PROFILE_ID IN ( select distinct (C1.Traffic_PROFILE_ID) from ");
//  builder.append(buildCosModelQuery(cosModel));

    for (int i = 1; i <= cosAllocation.size(); i++) {
            if (i > 1) builder.append(",");
        builder.append(" Cos_Class_Allocation c").append(i);
    }

    for (int i = 1; i <= cosAllocation.size(); i++) {
            builder.append(i == 1 ? " where " : " and ");
            builder.append("c").append(i).append(".class_name = ? AND c").append(i).append(".CLASS_ALLOCATION = ?");
        if (i > 1) {
                builder.append(" and C1.TRAFFIC_PROFILE_ID = c").append(i).append(".TRAFFIC_PROFILE_ID");
        }
    }

    builder.append(" )");

    return builder.toString();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Isolation in Resistive Current Sensor In resistive current sensor, can it have two different supplies for the voltage divider circuit and the differential op-amp circuit? Since the op-amp only gets the voltage difference.

A: If the grounds in your schematic are connected then the circuit will work fine with two different supplies as long as the voltage level reaching the opamp inputs is within the input common-mode range.
If the grounds are not connected then you can use a Hall-Effect-Based Linear Current Sensor such as ACS712. The sensor output is electrically isolated from the circuit being measured so the two supplies can  be completely independent.

A: I don't think your circuit will work in any event. The inverting input is connected to ground through a resistor, so the voltage at the inverting input is always at ground (for practical purposes). The voltage at the non-inverting input is above ground when there is current flowing, so the voltage at the output will increase. However, there is no feedback from the output to the inverting input because of how you have connected R3 to ground in the circuit. I think the connection from the right end of R3 needs to be connected between R5 and the inverting input.
Also, you are going to need an op amp with good rail-to-rail input and output to make this work for small currents.


text:
Q: Convert to int inside LINQ statement possible? I am wanting to save a record in a database using a simple LINQ statement. I am finding it is not possible to use a Convert.ToInt32 inside the linq statement like below:
using (var context = new Stc.LeadTracker.DataModel.Models.DBNameContext())
{
    var newLead = new DataModel.Models.LeadRequest();
    newLead.FormId = Convert.ToInt32(formId);
    newLead.Request = queryString;
    newLead.Success = true;
    newLead.RetryCount = 0;
    newLead.CreatedBy = nvCollection["iw"];
    newLead.CreatedDateTime = DateTime.Now;
    context.LeadRequests.Add(newLead);
    context.SaveChanges();
    leadId = newLead.LeadRequestId;
}

I can certainly do the conversion before the LINQ statement, was curious to know if that is my only option.

A: I would Convert.ToInt32(formId) before you get to the using statement.
Linq does not like Convert statements depending on the ORM
Check this out
Problem with converting int to string in Linq to entities

A: Did you try using int.Parse() or int.TryParse()?  Also, why are you not able to use Convert.ToInt32()?  Are you getting any errors?

A: You can cast the variable like this:
(int)formid
You have to check if "formId" can be casted to int.
using (var context = new Stc.LeadTracker.DataModel.Models.DBNameContext())
{
    var newLead = new DataModel.Models.LeadRequest();
    newLead.FormId = (int)formId;
    newLead.Request = queryString;
    newLead.Success = true;
    newLead.RetryCount = 0;
    newLead.CreatedBy = nvCollection["iw"];
    newLead.CreatedDateTime = DateTime.Now;
    context.LeadRequests.Add(newLead);
    context.SaveChanges();
    leadId = newLead.LeadRequestId;
}

There is a similar question here:
LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression


text:
Q: Calling a method based on value of variable I have 1000 methods called method0001, method0002 , ... ,method1000.
I have a variable that takes values between 1 and 1000.
If the value of the variable is x, I'd like to call methodx. For instance, if the value of the variable is 34, I'd like to call method0034. How can I code this in C# please?
Many people are asking what is need for Methodwxyz. Every method is a different type of math question.
i've done this, following the helpful comments but am getting errors (edited the question from earlier)
  using System.Collections.Generic;
 using UnityEngine;
  public class TextControl : MonoBehaviour
{
public static TextControl instance;

void Start()
{
   instance = this;
}
// Update is called once per frame
void Update()
{

        this.GetType().GetMethod("Template00" + "1").Invoke(this, null);

}
public static string Templates001()
{
    // doing something here
}
 }

thanks

A: You could do this through reflection.  Edit for a quick sample (forgot invoke parameters).  Some tips about reflection:

*

*If you get a nullexception that means it can't find the method

*The method you are invoking needs to be public

*If you use obfuscation you may not have the same names for the method

Code
public class Program
{
    public static void Main(string[] args)
    {
        Check method1 = new Check(1);
        Check method2 = new Check(2);
    }
}

public class Check
{
    public Check(int x)
    {
        this.GetType().GetMethod("Method" + x).Invoke(this, null);
    }

    public void Method1()
    {
        Console.WriteLine("Method 1");
    }

    public void Method2()
    {
        Console.WriteLine("Method 2");
    }
}


text:
Q: Laravel 5 how to clear cache using composer.json I am new to Laravel. I am trying to clear view cache, and I need to clear view cache without composer.
Is possible to clear cache using composer.json autoload?
I have already tried the code below, but it was not working.

routes.php

Route::get('/view-clear', function() {
    $exitCode = Artisan::call('view:clear');
    return '
View cache cleared
';
});

Also, how should I use...

Cache::flush();

...in my code controller.

A: With a Filemanager or a Simple PHP Code Delete the compiled views inside of storage\framework\views
Example:
Route::get('/view-clear', function() {
    $directory=storage_path('framework/views');
    $files=File::allFiles($directory);
    File::delete($files);
    return '
View cache cleared
';
});

A: May be something like this?
public function index()
    {
        $value = Cache::flush();

        return view('your.view')->with($value);
    }

A: Why not try clear browser cache ?
I think the view cache saved by browser.


text:
Q: After find() does ActiveRecord support accessing/seeking in memory row by particular field value (BESIDES seeking using primary key)? In the .Net universe I can use an arbitrary SELECT statement and load many rows into DataTable object.  I can then find various DataRows using various field criteria (Name='Jack', Age=34, etc.).
In Ruby on Rails, after doing this to load all employees into memory
rs = Employee.find(:all)

I want to seek a row based an arbitrary criteria.
row = rs.seek(:name => 'Jack')

Does ActiveRow support this?  I can't seem to find anything or I'm not using the correct terminology.
If not I'll have to walk all rows and build my own hash tables.

A: Employee.find(:all)

will return an array of ActiveRecord instances, so you can either search the array for the relevant records or do something like this:
row = Employee.find_by_name('Jack')

or
rows = Employee.find_all_by_name('Jack')

in order to select the rows you are interested in.

A: Assuming you have a really good reason for fetching all the data and then filtering it, as opposed to using Rails dynamic finders or scopes.
ActiveRecord find returns an Array as others have commented above.  You were really close, but the Array method you need is find (defined in module Enumerable)
all_employees = Employee.find(:all)

jack = all_employees.find { |employee| employee.name == 'Jack' }


text:
Q: getting id from POST request i'm watching a tutorial i'm watching a tutorials about CMS with OOP - PHP
on Control page :
public function Update()
{
    if(isset($_POST['updateArticle']))
    {
        $id = (int)$_POST['id'];

        //article data array
        //varaibles
        $title  = $_POST['title']; //title
        $content= $_POST['content']; //content
        $cat    = (int)$_POST['cat'];

        //Validation

        //data array

        $data = array(
            'title'   => $title,
            'content' => $content,
            'cid'     => $cat
        );

        //Insert
        if($this->articlesModel->Update($id,$data))
        {
            System::Get('tpl')->assign('message','Article Updated');
            System::Get('tpl')->draw('success');
        }
        else
        {
            System::Get('tpl')->assign('message','Error Updating article');
            System::Get('tpl')->draw('error');
        }

    }
    else
    {
        $id = 0 ; //init
        if(isset($_GET['id']) && (int)$_GET['id'] > 0)
        {
            $id = (int)$_GET['id'];

            //Get article from db
            $article = $this->articlesModel->Get_By_Id($id);

            if(count($article)>0)
            {
                //categories
                $cats = $this->articlesCatsModel->Get();

             //article found
                System::Get('tpl')->assign($article);
                System::Get('tpl')->assign('cats',$cats);
                System::Get('tpl')->draw('updatearticle');

            }
            else
            {
                //article not found
                System::Get('tpl')->assign('message','Article Not Found');
                System::Get('tpl')->draw('error');

            }

        }
        else
        {
            //no id
            System::Get('tpl')->assign('message','Ivalid ID');
            System::Get('tpl')->draw('error');
        }
    }

}

he get the id  from post request how !!!
we always take the id from url so GET Request
he did that because of this the source
source of the page:
<input type="hidden" name="id" value="5" />
<input type="submit" class="btn btn-info" name="updateArticle" value="Update Article" />

how can we take the id from post request !!
and if i changed it to GET request i get error

A: HTML Form tag has a method attribute. This attribute defines whether the content will be sent using POST or GET.
Check the method of the <form method=?>.
Read: http://www.w3schools.com/html/html_forms.asp


text:
Q: Stopping Camel Route when no more message in ActiveMQ Is there a way using which we can stop the Camel route if we don't have any more message in ActiveMQ? My required scenario.

*

*Fetch all the message from ActiveMQ queue and process them.

*Poll for 2-3 more times to check if we have any other new message, is yes execute step #1.

*If no message in present stop the route and start it back after say 5 min (which I guess can be achieved by Polling Strategy).

A: Have a look at this answer. It polls the queue with a scheduler and a polling strategy (POJO).

*

*With the scheduler you can choose the interval of polling

*With the timeout of the polling strategy consumer you can stop consuming (e.g. if no message arrives for 5 seconds the queue is probably empty)

If you want to stop/start the consumer completely, you can add Camel Control Bus to the mix. You could then start and stop the consumer route.


text:
Q: Could not find valid key in user session keyring for sig specified in mount option after upgrade from 16.04 to 18.04 About a month ago I updated my 16.04 LTS server to 18.04.1 LTS. The upgrade went fine. However, since the upgrade, whenever a user logs in, there is a message displayed in dmesg or on the local console (but not to the user's SSH session) that reads:
[890802.820519] Could not find key with description: [HEXSTRING]
[890802.820537] process_request_key_err: No key
[890802.820538] Could not find valid key in user session keyring for sig specified in mount option: [HEXSTRING]
[890802.820557] One or more global auth toks could not properly register; rc = [-2]
[890802.820558] Error parsing options; rc = [-2]

After much Googling, I found this related question and managed to figure out that it's a backup of the user's home drive taken when the upgrade occurred.
I should note that users still have access to their home drives and they do not have a problem logging in, this is just an annoyance message that I am trying to clean up.
I attempted to add the passphrase to the keyring using the accepted answer in the linked question:
$ /usr/bin/ecryptfs-manager

eCryptfs key management menu
-------------------------------
    1. Add passphrase key to keyring
    2. Add public key to keyring
    3. Generate new public/private keypair
    4. Exit

Make selection: 1

    Mount-wide passphrase:
    Confirm passphrase:
    Using the default salt value

That key was already in the keyring.

So, the key is already in the keyring but I still get the error message when a user logs in.
How can I prevent this notification/error from occurring?

A: It looks like this bug first reported in Ubuntu 17.10: ecryptfs-mount-private fails to initialize ecryptfs keys
The error there is like your own:
[ 1265.695388] Could not find key with description: [<correct key ID>]
[ 1265.695393] process_request_key_err: No key
[ 1265.695394] Could not find valid key in user session keyring for sig specified in mount option: [<correct key ID>]
[ 1265.695395] One or more global auth toks could not properly register; rc = [-2]
[ 1265.695396] Error parsing options; rc = [-2]

You should subscribe to the bug report and make sure you mark it affects you too.
Read the messages posted by other users. There are solutions that work for some and not others.

A: On Ubuntu 18.04 lts, Does this work for anyone?
exec /usr/bin/startfluxbox
and if you get a msg asking you to try running the interactive
ecryptfs-mount-private try doing that.
it should yield something like:

Inserted auth tok with sig  into the user session keyring INFO:
  Your private driectory has been mounted


text:
Q: MomentJS, FullCalendar time portions manipulation I use latest fullcalendar and momentjs. My timezone is GMT+0530
Steps of my process is;
Step 1) In Fullcalendar select:func(...) I capture the date/date-range user has selected to create an event. I get the start/end dates as a moment object. If I select one day; momentjs values are;
start: Wed Nov 01 2017 00:00:00 GMT+0000
end: Thu Nov 02 2017 00:00:00 GMT+0000
Question 1 - can't I make the end date to be on the same day? Otherwise Fullcalendar creates the event for 2 days. Currently I make it to work by substracting 1 day from moment (this doesn't look right).
Step 2) Using a slider I capture the events start/end time. In slider start/end are minutes from 0 to 1440 at opposite ends. I convert the selected time range to moment object by;
moment().startOf('day').add(start, 'minutes'); //slider's left drag
moment().startOf('day').add(end, 'minutes'); //slider's right drag

Step 3) - The time selected is set to the selected date in Step 1 using;
startDate.set({ 'hour': startTime.get('hour'), 'minute': startTime.get('minute') });

endDate.set({ 'hour': endTime.get('hour'), 'minute': endTime.get('minute') });

Now, the event start/end's moment.toString() shows as an example;
Date 1: Wed Nov 01 2017 07:00:00 GMT+0000
Date 2: Wed Nov 01 2017 12:30:00 GMT+0000 //I do a date.subtract(1, 'd') to avoid fullCalendar rendering the event to an additional day. Would like to know if there is a better way
Now the event I want is properly set to Wed Nov 01 2017 from 7AM to 12.30PM
Question 2 In Fullcalendar view rendering is correct. But in the event array; each moment object's dates are correct times have got reset.
Quite frustrating... so I just set FullCalendar aside and did some tests with momentjs using the final dates that should have worked.
Date 1: Wed Nov 01 2017 07:00:00 GMT+0000
Date 2: Wed Nov 01 2017 12:30:00 GMT+0000
I convert Date 1 to a moment object by using moment(startDate, 'date');
It creates a moment object and in Console it shows the date/time as I have above. Then if I do;
start.hour() or start.minute() //= 0

Above should give me hour = 07, minute = 00 not 0 for everything?
start.toString() // = Mon Nov 20 2017 00:00:00 GMT+0530
start.get('date') // = 20!!!!

But I expect it to give me back Wed Nov 01 2017 07:00:00 GMT+0000
Question 3 What am I doing wrong?


text: Q: Injetar componente dentro de outro componente Eu gostaria de saber, se eu posso injetar um componente dentro de outro componente, eu tenho uma função dentro de um componente e quando eu for fazer alguma coisa em outro componente, gostaria de chamar essa função do outro componente. Eu sei que existe o EventEmitter, porém gostaria de saber se pode acontecer algum erro. Aqui eu consegui fazer a função do outro componente e, é executada perfeitamente, porém desconheço se o uso disso possa trazer algum erro futuro. Utilizei o @Injectable() no componente que eu gostaria de utilizar no outro componente.


text:
Q: CoreAudio: Ausampler Unit polyphony I'm currently trying to use the Ausampler Unit efficiently. I used the code from apple's sample: https://developer.apple.com/library/ios/#samplecode/LoadPresetDemo/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011214-Intro-DontLinkElementID_2
The downside seems to be that it instantly stops a note/sampe if the same note comes in again.
So if I send e.g. midi note 60 with the trombone preset loaded. And then while holding this I send note 60 again. It cuts off the first note event. Does anyone know if/how it is possible to hold every single note till a note off event (of this specific note) comes in?
Other question:
How can I change the volume of a note after it has been send? E.g. I sent midi note 60 and 70 with 100 velocity. While note 60 still plays I want to reduce the volue but keep note 70 up. This would be called midi aftertouch.
Hope you can help :)

A: The AUSampler (kAudioUnitSubType_Sampler) is monotimbral (reference and here) so in order to play two notes of the same pitch simultaneously, you will need two "instruments" - i.e. to instances of the AUSampler. In my projects, I have found that this doesn't add much to the memory overhead since the sound resources get shared.
As for aftertouch - I haven't explored that but it seems like the property you want is kAUGroupParameterID_KeyPressure_FirstKey (References here, and maybe here).
Supporting the kAUGroupParameterID_KeyPressure parameter indicates to
hosts that your audio unit supports polyphonic "aftertouch" key pressure.

Each of the 128 MIDI key numbers can have its own value for polyphonic
aftertouch. To respond to aftertouch for a particular key, your audio
unit needs to support an additional parameter specifically for that key.
The aftertouch parameter ID for a given MIDI key is equal to the MIDI
key number plus 256. For example, the aftertouch parameter ID for MIDI
key #60 (middle C) is:

60 + kAUGroupParameterID_KeyPressure_FirstKey = 316

If you get aftertouch working, post back some sample code.

A: The accepted answer is WRONG. Timbre and Polyphony are two different things. Mono timbral means that the midi device (in this case the AUSampler instance) can only play a single INSTRUMENT/PATCH at the same time, that has nothing to do with the amount of concurrent notes it can play for that single instrument.
A multi timbral device on the other hand, can play several instruments/patches (midi channels) at the same time.
The polyphony seems to be limited and hardcoded to 2 notes in the iOS version of the AUSampler and there seems to be no public api to change that.

A: I don't think that AUSampler is limited to two note polyphony. I am just doing research for my project and it is very important for me.
Have a look at this piano keyboard plugin, author of it mentioned that it was made with AUSampler and from video you can see that it plays four note chords easily.


text:
Q: java "generic generic type" In my application, I have a Board. A Board consists of cell. Each cell has an int value.
There are few types of Boards that will extend Board.
Each type of Board will represent the cells differently. For example, one would use a List and anothr will use a Tree.
So this is what is tried:
public abstract class Board<T> {
    T<Cell> cells;  //error - The type T is not generic; it cannot be parameterized with arguments <Cell>

    protected abstract void setValues(T<Integer> values);
}

Unfortunately, I can't make T a generic type.
How do I implement that?

A: You would need to have something like:
public abstract class Board<T extends OtherGenericClass<TT>, TT> {
    T cells;
    public Board(T cells) {
        this.cells = cells;
    }
    protected abstract void setValues(T<Integer> values);

    public static void main(String[] args) {
        Cell<Integer> cells = new Cell<Integer>();
        Board<Cell<Integer>,Integer> board = new Board<Cell<Integer>,Integer>(cells);
    }
}

This does not seem like what you want though...I think you would rather have this:
public abstract class Board<T> {
    Cell<T>[] cells;
    public Board(Cell<T>[] cells) {
        this.cells = cells;
    }
}

with a Cell class:
public abstract class Cell<T> {
    T cellValue;
    public Cell(T cellValue) {
        return cellValue;
    }
}

A: I found your approach too complicated. Peter.petrov is close to what I will do.
If List and Tree (TreeSet) is what you need, both implements interface Collection so why not use this ?? Do you need anything extra to work with beside of add, removing, iterating ?
Collection (Javadoc)
So you class could look (I added little bit Java8 features)
public abstract class Board {
    Collection<Cell> cells;

    // Don't need to be abstract
    protected void setValues(Collection<Integer> values) {
        Stream<Cell> transformed = values.stream().map(Cell::new);
        cells.addAll(transformed.collect(Collectors.toList()));
    }
}

class Cell {
    private Integer value;

    Cell(Integer value) {
        this.value = value;
    }
}

If you need (for some reason something extra, extend this class and implement/override methods that will do special behaviour). Hopefully I helped, but I really don't see a use case for your example.

A: I don't really see much of a need to use generics here.
public abstract class Board {
    Holder<Cell> cells;

    protected abstract void setValues(Integer[] values);
}

Now have your List and Tree implement/extend Holder.
You can have 2 classes ListHolder and TreeHolder which both hold
cells but one is backed by a List, the other one by a Tree.
Actually maybe it makes more sense the setValues to be a
method on Holder which both ListHolder and TreeHolder implement.


text:
Q: SPA (Aurelia) + ASP.NET Core WebAPI + Google Authentication My SPA application (using Aurelia) calls my ASP.NET Core 2 Web API. I need to authenticate users with Google OIDC provider and also secure the Web API with the same method.
Currently I'm able to authenticate user on the client (SPA) side and retrieve id token and access token. With each API call I send the access token in the header.
Now I'm not sure how to handle the server side to validate the token and grant or deny the access to the API. I followed official docs how to add external login providers, but it seem to work only for server-side MVC applications.
Is there any easy way how to do this?
I think for instance IdentityServer4 can support this scenario, but it seems to me too complex for what I need to do. I don't need my own identity/authorization server after all.
Update:
Based on Miroslav Popovic answer, my configuration for ASP.NET Core 2.0 looks like this:
public void ConfigureServices(IServiceCollection services)
{
  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
  {
    o.Authority = "https://accounts.google.com";
    o.TokenValidationParameters = new TokenValidationParameters
    {
      ValidIssuer = "accounts.google.com",
      ValidAudience = "xxxxxxxxxxxxx.apps.googleusercontent.com",
      ValidateAudience = true,
      ValidateIssuer = true
    };
  });

  services.AddMvc();
}

And in Configure() I call app.UseAuthentication().
When using this setup I get failure message No SecurityTokenValidator available for token.
Update 2:
I made it work. The server configuration is correct. The problem was I was sending access_token to the API instead of id_token.

A: Since you already have the access token, it shouldn't be too hard to use it to add authentication. You would need something along these lines (not tested):
// Inside Startup.cs, ConfigureServices method
services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(
        options =>
        {
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = "accounts.google.com",
                ValidateAudience = false
            };

            options.MetadataAddress = "https://accounts.google.com/.well-known/openid-configuration";
            options.TokenValidationParameters = tokenValidationParameters;
    });

// Inside Startup.cs, Configure method
app.UseAuthentication(); // Before MVC middleware
app.UseMvc();

// And of course, on your controllers:
[Authorize]
public class MyApiController : Controller

This post from Paul Rowe might help some more, but note that it's written for ASP.NET Core 1.x and authentication APIs changed a bit in 2.0.
There is also a lot of info here on SO, like this question.


text:
Q: Is it possible to filter foreignkeys with a queryset? Django I just updated django from 1.8.5 to 1.10.
In the old Version i used a filter to search for entries regarding more then one location. For example:
One User has multiple Stores. Each of this Stores has a Reviews Board.
Now the User wants to lookup all Stores and their Reviews or specific Groups of Stores.
In Django 1.8.5 i used the following lookup:
all stores
locations = Locations.objects.filter(email=email)

locations queryset(location1, location2 etc.)
reviews = Reviews.objects.filter(location_id=locations)

group
reviews = Reviews.objects.filter(location_id=group_content.locations.all())

In Reviews the location field is a ForeignKey(Locations) and locations is a Queryset.
This worked just fine. However in 10.10 it appears this functionality is gone.
I looked through the new Docs but could not find anything which could replicate the original functionality.
My whole System is built around this functionality, so it would take forever to change everything.
Is there any new Lookup i could use?
models.py (Reviews):
class Reviews(models.Model):
    location_adress = models.CharField(max_length=3000, default='', blank=True, null=True)
    location_name = models.CharField(max_length=3000, default='', blank=True, null=True)

    location_id =  models.ForeignKey(LocationData)
    plattform =  models.CharField(max_length=3000, default='', blank=True, null=True)

    reviewer_name = models.CharField(max_length=3000, default='', blank=True, null=True)
    reviewer_picture = models.CharField(max_length=3000, default='', blank=True, null=True)
    review_id =  models.CharField(max_length=3000, default='', blank=True, null=True)
    review_rating =  models.CharField(max_length=3000, default='', blank=True, null=True)
    review_date = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
    review_text = models.CharField(max_length=3000, default='', blank=True, null=True)
    review_like_count = models.CharField(max_length=3000, default='', blank=True, null=True)
    review_share_count = models.CharField(max_length=3000, default='', blank=True, null=True)
    review_comment_count = models.CharField(max_length=3000, default='', blank=True, null=True)
    review_image = models.CharField(max_length=3000, default='', blank=True, null=True)
    next_entry =  models.CharField(max_length=3000, default='', blank=True, null=True)
    seen = models.BooleanField(default=False)
    unseen_comments_count = models.IntegerField(default=0, null=True)
    comments = models.ManyToManyField(ReviewComments)
    scale = models.IntegerField(default=None,blank=True, null=True)

    def __str__(self):
        return self.location_name

modely.py (Locations)
   class LocationData(models.Model):
        #Location Data
        group_id = models.CharField(max_length=120, default='', blank=True, null=True)
        location_id =  models.CharField(max_length=120, default='', blank=True, null=True)
        email = models.EmailField()
        name = models.CharField(max_length=120, default='', blank=True, null=True)
        street = models.CharField(max_length=120, default='', blank=True, null=True)
        street_number = models.CharField(max_length=120, default='', blank=True, null=True)
        opening = models.DateTimeField(auto_now_add=False, auto_now=True)
        tel = models.CharField(max_length=120, default='', blank=True, null=True)
        postal_code = models.CharField(max_length=120, default='', blank=True, null=True)
        city = models.CharField(max_length=120, default='', blank=True, null=True)
        country = models.CharField(max_length=120, default='', blank=True, null=True)
        description = models.CharField(max_length=1120, default='', blank=True, null=True)
        short_description = models.CharField(max_length=1120, default='', blank=True, null=True)
        website = models.CharField(max_length=120, default='', blank=True, null=True)
        location_email = models.CharField(max_length=120, default='', blank=True, null=True)
        tags = models.CharField(max_length=120, default='', blank=True, null=True)
        profilbild = models.CharField(max_length=320, default='', blank=True, null=True)
        titelbild = models.CharField(max_length=320, default='', blank=True, null=True)
  def __str__(self): #Python 3.3 is __str__
    return self.name

Result:
    >>> from reviews.models import Reviews
    >>> from locations.models import LocationData
    >>> l = LocationData.objects.all()
    >>> Reviews.objects.filter(location_id=l)
    <QuerySet [<Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>]>

>>> Reviews.objects.filter(location_id=l[0])
<QuerySet [<Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>, <Reviews: Bspotted>]>
>>> Reviews.objects.filter(location_id=l[1])
<QuerySet [<Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, <Reviews: Roberto American Bar>, '...(remaining elements truncated)...']>

A: l is a queryset, not a single object, so you should do something like that:
Reviews.objects.filter(location__in=l)


text:
Q: Divide / split string based on spaces by n-value I'm trying to divide the string based on the spaces on the string, if I divide the string into a n value, the output should be array with 3 values
I have this string for example "SIZZLING STEAK TERIYAKI BOY" and I want to divide this string into 3 based on spaces, the output should be ["SIZZLING STEAK", "TERIYAKI", "BOY"];
Another example is my string is "POWERVILLE FUN RIDES" and if I will divide this into 2, the output should be ["POWERVILLE FUN", "RIDES"] and if I will divide this string into 3, the output should be ["POWERVILLE", "FUN", "RIDES"];
function getSplitedText(number, word) {
 let splitedText = word.split(" ");
 let a = "";
 let b = [];
 let ctr = 1;
 for (let i = 0; i < splitedText.length; i++) {
  if (ctr === Math.ceil(splitedText.length / number)) {
   a += splitedText[i];
   b.push(a);
   a = "";
   ctr = 1;
 } else {
   a += splitedText[i] += " ";
   ctr++;
 }

 if (i === splitedText.length - 1) {
   if (a !== "")  b.push(a);
 }
}

return b;
}

let ans = getSplitedText(3, "SIZZLING STEAK TERIYAKI BOY");
document.write(ans)

Here is my current code for this one: https://jsfiddle.net/nesvcz1w/
on this fiddle the string "SIZZLING STEAK TERIYAKI BOY" became ["SIZZLING STEAK, TERIYAKI BOY"] which is wrong, it should be ["SIZZLING STEAK", "TERIYAKI", "BOY"];

A: At first we can split our string into array words. Let's call it splitted. Then we can make a decision based on breaker whether word should be concatenated or pushed as whole word:
fooDivider = (str, num) => {
    let splitted = str.split(' ');
    let breaker = (splitted.length - num) + 1;

    const joined = splitted.splice(0, breaker).join(' ');
    return [joined, ...splitted];
}

An example:

let str = "POWERVILLE FUN RIDES";

fooDivider = (str, num) => {
   let splitted = str.split(' ');
   let breaker = (splitted.length - num) + 1;

   const joined = splitted.splice(0, breaker).join(' ');
   return [joined, ...splitted];
}

console.log(fooDivider("SIZZLING STEAK TERIYAKI BOY", 3));
console.log(fooDivider("POWERVILLE FUN RIDES", 2));

A: const splitText = (str, n) => {
  const strArray = str.split(" ");
  if(n === strArray.length) {
    return strArray;
  } else if(n < strArray.length) {
    const combine = strArray.slice(0, (strArray.length-n)+1)
    const defaultSet = strArray.slice((strArray.length-n)+1, strArray.length)
    return [...[combine.join(" ")], ...defaultSet]
  } else {
    return []
  }
}

const ans1 = splitText("SIZZLING STEAK TERIYAKI BOY", 3);
console.log("ans 1", ans1);
const ans2 = splitText("POWERVILLE FUN RIDES", 2);
console.log("ans 2", ans2);
const ans3 = splitText("POWERVILLE FUN RIDES", 3);
console.log("ans 3", ans3);

Hope this will solve your problem.

A: This will suit your needs.
  function getSplitedText(number, word) {
    var indexes = dotIndexes(word);
    let splitedText = word.split(" ");
    if (number == indexes.length + 1) {
      //full parse
      return splitedText;
    } else {
      //just latest ones
      let combinedParts = "";
      let partsOfResult = [number];
      for (let counter = 0; counter < splitedText.length; counter++) {
        var element = splitedText[counter];
        if (counter > 1) {
          partsOfResult[counter-1] = element;
          //console.log("seperate :" + splitedText[counter] + counter);
        } else {
          combinedParts += " ";
          combinedParts += element;
          //console.log("combine :" + splitedText[counter] + counter);
        }
      }
      combinedParts = combinedParts.trim();
      partsOfResult[0] = combinedParts;
      return partsOfResult;
    }
  }
  function dotIndexes(word) {
    var indices = [];
    for (var i = 0; i < word.length; i++) {
      if (word[i] === " ") indices.push(i);
    }
    return indices;
  }
  var myWord = "SIZZLING STEAK TERIYAKI BOY";
  var myWord2 = "POWERVILLE FUN RIDES";
  console.log(getSplitedText(3, myWord));
  console.log(getSplitedText(4, myWord));
  console.log(getSplitedText(2, myWord2));
  console.log(getSplitedText(3, myWord2));

A: Perhaps you may do like;

function fun(t,n){
  var ws = t.split(/\s+/);
  return [].concat( ws.slice(0,n)
                      .join(" ")
                  , ws.slice(n)
                  );
}

var t1 = "SIZZLING STEAK TERIYAKI BOY",
    t2 = "POWERVILLE FUN RIDES";

console.log(fun(t1,2));
console.log(fun(t2,2));


text:
Q: Pyenv and Conda coexisting I want to use pyenv and conda. Pyenv for managing my python versions and conda mostly for Jupiter Notebook. However, every time I use conda it overrides pyenv paths and sets local python version for it's one.
This is the .zshrc file on my MacBook pro with os 12 on it.
#<<<<<<<<<<<<<<<<CONDA>>>>>>>>>>>>>>>>>
export PATH="/Users/potato/anaconda3/bin:$PATH"
#<<<<<<<<<<<<<<<<CONDA>>>>>>>>>>>>>>>>>

#<<<<<<<<<<<<<<<<PYENV>>>>>>>>>>>>>>>>>
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
export PATH="$HOME/.pyenv/bin:$PATH"
export PATH="/usr/local/bin:$PATH"
export LDFLAGS="-L/usr/local/opt/zlib/lib -L/usr/local/opt/bzip2/lib"
export CPPFLAGS="-I/usr/local/opt/zlib/include -I/usr/local/opt/bzip2/include"
#<<<<<<<<<<<<<<<<PYENV>>>>>>>>>>>>>>>>>

I tried different solutions like this: Installing anaconda with pyenv, unable to configure virtual environment
Still doesn't work
Ideally, I would want to just switch from python to conda and be able to use Jupiter notebook, then when I'm done write a simple command that would return to pyenv control of versions.

A: Thank you merv.
I could've done it much easier.
Here's what I did.
I created virtualenv with pyenv, downloaded jupyter notebook with pip while in the virtual environment and voila, so easy. Almost like I didn't have to download whole anaconda to do it XD


text:
Q: PrestaShop: Translating overrided controller I've created a module that overrides an AdminProductController.php and make a new bulk_action.
<?php
class AdminProductsController extends AdminProductsControllerCore
{
    public function __construct()
    {
        parent::__construct();
        $this->bulk_actions['setprice'] = array(
            'text' => $this->l('Set a price for selected'),
            'icon' => 'icon-price',
        );
    }
}

Now I need to translate the action text and distribute that translation with module.
The problem is that I don't see the original text inside modules translation instead it is visible in back-office translations.
So, is there any way to add this string to module translations not to back-office translations?

A: You can do it by creating an instance of a module you want the translation to be in.
class AdminProductsController extends AdminProductsControllerCore
{
    public function __construct()
    {
        parent::__construct();
        $module = Module::getInstanceByName('modulename');
        $this->bulk_actions['setprice'] = array(
            'text' => $module->l('Set a price for selected'),
            'icon' => 'icon-price',
        );
    }
}

A: The main problem description I've found here: How to get translation from other module in PrestaShop?

This is because translations controller scans for $this->l((.*)) inside module folder using regex and adds the translatable strings to a file
  So we should in module do something like this:

class MyModule extends Module
{

    public static $l = null;
    public function __construct()
    {
        parent::__construct();
        $this::$l = $this->l('Set a price for selected');
    }
}

Than in controller we can do what was suggested by @TheDrot:
class AdminProductsController extends AdminProductsControllerCore
{
    public function __construct()
    {
        parent::__construct();
        $module = Module::getInstanceByName('modulename');
        $this->bulk_actions['setprice'] = array(
            'text' => $module->l('Set a price for selected'),
            'icon' => 'icon-price',
        );
    }
}

A: Try using the following code in place of $this->l('Set a price for selected')
Translate::getModuleTranslation(YOUR_MODULE_NAME, 'Set a price for selected', FILE_NAME);


text:
Q: Oracle SQL Pivot Multiple Columns I have a data set where 1 LICENSE_ID has been split into multiple rows.  I would like to combine the rows so I have 1 row per PERSON_ID and LICENSE_ID combination.
Here is how my data is formatted:
SELECT '123456789' AS PERSON_ID, '1' AS LICENSE_ID, 'NUMBER' AS FIELD, '123' AS EXPECTED, '124' AS ACTUAL, 'UPDATE' AS ACTION FROM DUAL UNION ALL
SELECT '123456789' AS PERSON_ID, '1' AS LICENSE_ID, 'ISSUE_DT' AS FIELD, '43498' AS EXPECTED, '43498' AS ACTUAL, 'NA' AS ACTION FROM DUAL UNION ALL
SELECT '123456789' AS PERSON_ID, '2' AS LICENSE_ID, 'NUMBER' AS FIELD, '888' AS EXPECTED, '888' AS ACTUAL, 'NA' AS ACTION FROM DUAL UNION ALL
SELECT '123456789' AS PERSON_ID, '2' AS LICENSE_ID, 'ISSUE_DT' AS FIELD, '43498' AS EXPECTED, '' AS ACTUAL, 'UPDATE' AS ACTION FROM DUAL

The table looks like this:

The output I need is like this:

A: You can use conditional aggregation:
select person_id, licence_id,
       max(case when field = 'NUMBER' then expected end) as expected_number,
       max(case when field = 'NUMBER' then actual end) as actual_number,
       max(case when field = 'NUMBER' then actual end) as actual_number,
       max(case when field = 'ISSUE_DT' then expected end) as expected_issue_dt,
       max(case when field = 'ISSUE_DT' then actual end) as actual_issue_dt,
       max(case when field = 'ISSUE_DT' then action end) as actual_issue_dt_action,
from t
group by person_id, licence_id


text:
Q: Arbitrary acceleration written as centripetal acceleration of approximating circle Suppose I want to find the acceleration of a projectile given its trajectory, i.e. its space coordinates as functions of time.
I have heard that the acceleration can always be written as the centripetal acceleration of the circle approximating the motion, but I do not understand this quantitatively.
Can someone explain this correspondence?

A: For an object on some trajectory the acceleration is defined by the usual equation:
$$ \mathbf{a} = \frac{d\mathbf{v}}{dt} $$
where both $\mathbf{a}$ and $\mathbf{v}$ are vectors, so this is a vector equation. Any trajectory can be locally approximated by its osculating circle, and the acceleration will then have the magnitude $v^2/r$, where $r$ is the radius of this circle, and it will be directed towards the centre of the circle.
Whether this is useful depends on the details of the trajectory. Although it applies to any trajectory, you replace the problem of calculating the acceleration directly with the problem of calculating the osculating circle, and both the position and radius of the circle will be functions of time. It's not obvious why calculating the osculating circle would be easier.


text:
Q: Driver class not found I`m getting an error in my Maven mysql project in netbeans when I try and clean build. The error is:
Failed to execute goal org.codehaus.mojo:sql-maven-plugin:1.5:execute (default) on project utopiaDatabase: Driver class not found: com.mysql.jdbc.Driver

I looked around and figured this is probably because my project isn`t finding my mysql-connector-java, but I have it added as a dependency and everything in my POM file looks fine, do you know why it might not be finding it?
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.eeu46f</groupId>
<artifactId>utopiaDatabase</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<profiles>
    <profile>
        <id>hsql</id>
        <dependencies>
            <dependency>
                <groupId>org.hsqldb</groupId>
                <artifactId>hsqldb</artifactId>
                <version>2.3.2</version>
                <classifier>jdk6debug</classifier>
            </dependency>
        </dependencies>
        <properties>
            <jdbc.url>jdbc:hsqldb:mem:testDB</jdbc.url>
            <jdbc.username>SA</jdbc.username>
            <jdbc.password></jdbc.password>
            <jdbc.driver>org.hsqldb.jdbc.JDBCDriver</jdbc.driver>
        </properties>
    </profile>
    <profile>
        <id>mysql</id>
        <dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.6</version>
                <scope>runtime</scope>
            </dependency>
        </dependencies>
        <properties>
            <jdbc.url>jdbc:mysql:taken out for security</jdbc.url>
            <jdbc.username>taken out for security</jdbc.username>
            <jdbc.password>taken out for security</jdbc.password>
            <jdbc.driver>com.mysql.jdbc.Driver</jdbc.driver>
        </properties>
    </profile>
</profiles>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-collections4</artifactId>
        <version>4.1</version>
    </dependency>
    <dependency>
        <groupId>org.hsqldb</groupId>
        <artifactId>hsqldb</artifactId>
        <version>2.3.2</version>
        <classifier>jdk6debug</classifier>
    </dependency>
    <dependency>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>sql-maven-plugin</artifactId>
        <version>1.5</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
</dependencies>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
</properties>
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>sql-maven-plugin</artifactId>
            <version>1.5</version>
            <configuration>
                <driver>${jdbc.driver}</driver>
                <url>${jdbc.url}</url>
                <username>${jdbc.username}</username>
                <password>${jdbc.password}</password>
            </configuration>
            <executions>
                <execution>
                    <phase>generate-test-resources</phase>
                    <goals>
                        <goal>execute</goal>
                    </goals>
                    <configuration>
                        <srcFiles>
                            <srcFile>src/test/resources/1-destroy.sql</srcFile>
                            <srcFile>src/test/resources/2-create.sql</srcFile>
                            <srcFile>src/test/resources/3-insert.sql</srcFile>
                        </srcFiles>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

<name>utopiaDatabase</name>

database properties file in src/main/resources:
jdbc.url=${jdbc.url}
jdbc.username=${jdbc.username}
jdbc.password=${jdbc.password}
jdbc.driver=${jdbc.driver}

I have tried adding mysql-connector-java-5.1.6 as a dependency in my maven project manually also. Thanks in advance

A: If you look at the homepage of the sql-maven-plugin under "Usage" it clearly shows that you have to give your driver as a dependency to the sql-maven-plugin. You only gave it as a dependency of your project.
If your project needs that dependency as well or not is a different story.


text:
Q: get UTC timestamp in python with datetime Is there a way to get the UTC timestamp by specifying the date? What I would expect:
datetime(2008, 1, 1, 0, 0, 0, 0)

should result in
 1199145600

Creating a naive datetime object means that there is no time zone information. If I look at the documentation for datetime.utcfromtimestamp, creating a UTC timestamp means leaving out the time zone information. So I would guess, that creating a naive datetime object (like I did) would result in a UTC timestamp. However:
then = datetime(2008, 1, 1, 0, 0, 0, 0)
datetime.utcfromtimestamp(float(then.strftime('%s')))

results in
2007-12-31 23:00:00

Is there still any hidden time zone information in the datetime object? What am I doing wrong?

A: I feel like the main answer is still not so clear, and it's worth taking the time to understand time and timezones.
The most important thing to understand when dealing with time is that time is relative!

*

*2017-08-30 13:23:00: (a naive datetime), represents a local time somewhere in the world, but note that 2017-08-30 13:23:00 in London is NOT THE SAME TIME as 2017-08-30 13:23:00 in San Francisco.

Because the same time string can be interpreted as different points-in-time depending on where you are in the world, there is a need for an absolute notion of time.
A UTC timestamp is a number in seconds (or milliseconds) from Epoch (defined as 1 January 1970 00:00:00 at GMT timezone +00:00 offset).
Epoch is anchored on the GMT timezone and therefore is an absolute point in time. A UTC timestamp being an offset from an absolute time therefore defines an absolute point in time.
This makes it possible to order events in time.
Without timezone information, time is relative, and cannot be converted to an absolute notion of time without providing some indication of what timezone the naive datetime should be anchored to.
What are the types of time used in computer system?

*

*naive datetime: usually for display, in local time (i.e. in the browser) where the OS can provide timezone information to the program.

*UTC timestamps: A UTC timestamp is an absolute point in time, as mentioned above, but it is anchored in a given timezone, so a UTC timestamp can be converted to a datetime in any timezone, however it does not contain timezone information. What does that mean? That means that 1504119325 corresponds to 2017-08-30T18:55:24Z, or 2017-08-30T17:55:24-0100 or also 2017-08-30T10:55:24-0800. It doesn't tell you where the datetime recorded is from. It's usually used on the server side to record events (logs, etc...) or used to convert a timezone aware datetime to an absolute point in time and compute time differences.

*ISO-8601 datetime string: The ISO-8601 is a standardized format to record datetime with timezone. (It's in fact several formats, read on here: https://en.wikipedia.org/wiki/ISO_8601) It is used to communicate timezone aware datetime information in a serializable manner between systems.
When to use which? or rather when do you need to care about timezones?

*

*If you need in any way to care about time-of-day, you need timezone information. A calendar or alarm needs time-of-day to set a meeting at the correct time of the day for any user in the world. If this data is saved on a server, the server needs to know what timezone the datetime corresponds to.

*To compute time differences between events coming from different places in the world, UTC timestamp is enough, but you lose the ability to analyze at what time of day events occured (ie. for web analytics, you may want to know when users come to your site in their local time: do you see more users in the morning or the evening? You can't figure that out without time of day information.
Timezone offset in a date string:
Another point that is important, is that timezone offset in a date string is not fixed. That means that because 2017-08-30T10:55:24-0800 says the offset -0800 or 8 hours back, doesn't mean that it will always be!
In the summer it may well be in daylight saving time, and it would be -0700
What that means is that timezone offset (+0100) is not the same as timezone name (Europe/France) or even timezone designation (CET)
America/Los_Angeles timezone is a place in the world, but it turns into PST (Pacific Standard Time) timezone offset notation in the winter, and PDT (Pacific Daylight Time) in the summer.
So, on top of getting the timezone offset from the datestring, you should also get the timezone name to be accurate.
Most packages will be able to convert numeric offsets from daylight saving time to standard time on their own, but that is not necessarily trivial with just offset. For example WAT timezone designation in West Africa, is UTC+0100 just like CET timezone in France, but France observes daylight saving time, while West Africa does not (because they're close to the equator)
So, in short, it's complicated. VERY complicated, and that's why you should not do this yourself, but trust a package that does it for you, and KEEP IT UP TO DATE!

A: Another possibility is:
d = datetime.datetime.utcnow()
epoch = datetime.datetime(1970,1,1)
t = (d - epoch).total_seconds()

This works as both "d" and "epoch" are naive datetimes, making the "-" operator valid, and returning an interval. total_seconds() turns the interval into seconds. Note that total_seconds() returns a float, even d.microsecond == 0

A: Also note the calendar.timegm() function as described by this blog entry:
import calendar
calendar.timegm(utc_timetuple)

The output should agree with the solution of vaab.

A: There is indeed a problem with using utcfromtimestamp and specifying time zones. A nice example/explanation is available on the following question:
How to specify time zone (UTC) when converting to Unix time? (Python)

A: A simple solution without using external modules:
from datetime import datetime, timezone

dt = datetime(2008, 1, 1, 0, 0, 0, 0)
int(dt.replace(tzinfo=timezone.utc).timestamp())

A: If input datetime object is in UTC:
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
1199145600.0

Note: it returns float i.e., microseconds are represented as fractions of a second.
If input date object is in UTC:
>>> from datetime import date
>>> utc_date = date(2008, 1, 1)
>>> timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
1199145600

See more details at Converting datetime.date to UTC timestamp in Python.

A: Naïve datetime versus aware datetime
Default datetime objects are said to be "naïve": they keep time information without the time zone information. Think about naïve datetime as a relative number (ie: +4) without a clear origin (in fact your origin will be common throughout your system boundary).
In contrast, think about aware datetime as absolute numbers (ie: 8) with a common origin for the whole world.
Without timezone information you cannot convert the "naive" datetime towards any non-naive time representation (where does +4 targets if we don't know from where to start ?). This is why you can't have a datetime.datetime.toutctimestamp() method. (cf: http://bugs.python.org/issue1457227)
To check if your datetime dt is naïve, check dt.tzinfo, if None, then it's naïve:
datetime.now()        ## DANGER: returns naïve datetime pointing on local time
datetime(1970, 1, 1)  ## returns naïve datetime pointing on user given time

I have naïve datetimes, what can I do ?
You must make an assumption depending on your particular context:
The question you must ask yourself is: was your datetime on UTC ? or was it local time ?

*

*If you were using UTC (you are out of trouble):
import calendar

def dt2ts(dt):
    """Converts a datetime object to UTC timestamp

    naive datetime will be considered UTC.

    """

    return calendar.timegm(dt.utctimetuple())

*If you were NOT using UTC, welcome to hell.
You have to make your datetime non-naïve prior to using the former
function, by giving them back their intended timezone.
You'll need the name of the timezone and the information about
if DST was in effect when producing the target naïve datetime (the
last info about DST is required for cornercases):
import pytz     ## pip install pytz

mytz = pytz.timezone('Europe/Amsterdam')             ## Set your timezone

dt = mytz.normalize(mytz.localize(dt, is_dst=True))  ## Set is_dst accordingly

Consequences of not providing is_dst:
Not using is_dst will generate incorrect time (and UTC timestamp)
if target datetime was produced while a backward DST was put in place
(for instance changing DST time by removing one hour).
Providing incorrect is_dst will of course generate incorrect
time (and UTC timestamp) only on DST overlap or holes. And, when
providing
also incorrect time, occuring in "holes" (time that never existed due
to forward shifting DST), is_dst will give an interpretation of
how to consider this bogus time, and this is the only case where
.normalize(..) will actually do something here, as it'll then
translate it as an actual valid time (changing the datetime AND the
DST object if required). Note that .normalize() is not required
for having a correct UTC timestamp at the end, but is probably
recommended if you dislike the idea of having bogus times in your
variables, especially if you re-use this variable elsewhere.
and AVOID USING THE FOLLOWING: (cf: Datetime Timezone conversion using pytz)
dt = dt.replace(tzinfo=timezone('Europe/Amsterdam'))  ## BAD !!

Why? because .replace() replaces blindly the tzinfo without
taking into account the target time and will choose a bad DST object.
Whereas .localize() uses the target time and your is_dst hint
to select the right DST object.
OLD incorrect answer (thanks @J.F.Sebastien for bringing this up):
Hopefully, it is quite easy to guess the timezone (your local origin) when you create your naive datetime object as it is related to the system configuration that you would hopefully NOT change between the naive datetime object creation and the moment when you want to get the UTC timestamp. This trick can be used to give an imperfect question.
By using time.mktime we can create an utc_mktime:
def utc_mktime(utc_tuple):
    """Returns number of seconds elapsed since epoch

    Note that no timezone are taken into consideration.

    utc tuple must be: (year, month, day, hour, minute, second)

    """

    if len(utc_tuple) == 6:
        utc_tuple += (0, 0, 0)
    return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0))

def datetime_to_timestamp(dt):
    """Converts a datetime object to UTC timestamp"""

    return int(utc_mktime(dt.timetuple()))

You must make sure that your datetime object is created on the same timezone than the one that has created your datetime.
This last solution is incorrect because it makes the assumption that the UTC offset from now is the same than the UTC offset from EPOCH. Which is not the case for a lot of timezones (in specific moment of the year for the Daylight Saving Time (DST) offsets).

A: The accepted answer seems not work for me. My solution:
import time
utc_0 = int(time.mktime(datetime(1970, 01, 01).timetuple()))
def datetime2ts(dt):
    """Converts a datetime object to UTC timestamp"""
    return int(time.mktime(dt.utctimetuple())) - utc_0

A: Simplest way:

>>> from datetime import datetime
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> dt.strftime("%s")
'1199163600'

Edit: @Daniel is correct, this would convert it to the machine's timezone. Here is a revised answer:
>>> from datetime import datetime, timezone
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> int((dt-epoch).total_seconds())
'1199145600'

In fact, its not even necessary to specify timezone.utc, because the time difference is the same so long as both datetime have the same timezone (or no timezone).
>>> from datetime import datetime
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> int((dt-epoch).total_seconds())
1199145600

A: I think the correct way to phrase your question is
Is there a way to get the timestamp by specifying the date in UTC?, because timestamp is just a number which is absolute, not relative. The relative (or timezone aware) piece is the date.
I find pandas very convenient for timestamps, so:
import pandas as pd
dt1 = datetime(2008, 1, 1, 0, 0, 0, 0)
ts1 = pd.Timestamp(dt1, tz='utc').timestamp()
# make sure you get back dt1
datetime.utcfromtimestamp(ts1)


text:
Q: Spurious renaming in nested Function construct From the documentation of Function, I take this example (slightly simplified). Renaming the dummy or bound variable (y->y$ in the inner Function) is necessary in:
In[1206]:= Function[x, Function[y, f[x, y]]][y]
Out[1206]= Function[y$, f[y, y$]]

so that, for example,
In[1215]:= Function[x, Function[y, f[x, y]]][y][1]
Out[1215]= f[y, 1]

because
In[1211]:= Function[y$, f[y, y$]][1]
Out[1211]= f[y, 1]

Without renaming, we would obtain a different and generally wrong value
In[1212]:= Function[y, f[y, y]][1]
Out[1212]= f[1, 1]

The documentation shows that renaming occurs even if it is not necessary:
In[1213]:= Function[x, Function[y, f[x, y]]][1]
Out[1213]= Function[y$, f[1, y$]]

Indeed, the choice of parameter name y should have no consequence on the function value.
Now let me try:
 In[1214]:= Function[x, Function[y, f[x, y]]][y$]
 Out[1214]= Function[y$, f[y$, y$]]

which is the same as Function[y, f[y, y]] that is wrong, as explained above.
So it looks to me like a plain fat bug, is not it?
Edited after comments
The bug is equivalent to:
In[1335]:= With[{x = y$}, Function[y, f[x, y]]]
Out[1335]= Function[y$, f[y$, y$]]

In this related case on the contrary no renaming occurs:
In[1338]:= Function[y, f[x, y]] /. x -> y$
Out[1338]= Function[y, f[y$, y]]

That is because the job of ReplaceAll is just to replace, not to detect name conflict.

A: If you use $ signs at the end of variable names in Function in Manipulate, you're asking for trouble.
Manipulate[
 Function[x, Function[y, f[x, y$]]][y$$],
 {y, 0, 1}]

Manipulate[
 y$$$ + y$$$$ + y$$$$$ + Function[x, Function[y, f[x, y]]][y$$],
 {y$$$$$, 1, 2}]

Manipulate[
 y$$$ + y$$$$ + y$$$$$ + Function[x, Function[y, f[x, y]]][y$$$],
 {y$$$$$, 1, 2}]

The explanation is that Manipulate strips and adds dollar signs according to its own secret rules, maybe after thumb wrestling with Function, which is not really an explanation. The results always seem to be the same. Maybe not from version to version. I didn't check.

A: From the documentation of Function in Mathematica:

The named formal parameters Subscript[x, i] in
Function[{Subscript[x, 1],\[Ellipsis]},body]
are treated as local, and are renamed
Subscript[x, i]$ when necessary to avoid confusion with actual
arguments supplied to the function.

One missing information in this laconic description is that single \$-ended formal parameters, corresponding to the string expression ___ ~~ Except@"$" ~~ "$", e. g. t$, but not t$$, are never renamed.
The renaming mechanism (called α-conversion in λ-calculus) appears in the minimal case
In[3]:= Function[t, Function[u, y[t, u]]]@v
Out[3]= Function[u$, y[v, u$]]

Semantically, for a faithful model of a mathematical (partial) function, renaming is only needed if the value of v is u (v==u):
In[4]:= Function[t, Function[u, y[t, u]]]@u
Out[4]= Function[u$, y[u, u$]]

The Wolfram language model of function is thus overcautious.  For example, renaming occurs without need in
In[7]:= Function[t, Function[u, y[t, u]]]@1
Out[7]= Function[u$, y[1, u$]]

I suppose that this overcautiousness is intended by design to save the test u==v run time.
If ever you want to avoid unneeded renaming, you can, by using single \$-ended in the first place:
In[9]:= Function[t, Function[u$, y[t, u$]]]@1
Out[9]= Function[u$, y[1, u$]]

Thus Michael E2's rule "Don't ever end your variables with a \$." is safe but also overcautious for the following reasons:

*

*Single \$-ended names are useful (or intended by design) to avoid renaming.

*Names ending with at least two \$ like t$$ are perfectly safe for Function (although elsewhere I can't assert).


text:
Q: Como extraer año, mes y día como, individual desde un dato DateTime, con dart Tengo esta función pero me devuelve 2020/12/16, y quiero que me devuelta el año en tipo int 2020, el mes tipo int 12, y día tipo int 16.
este es mi código por favor a ver si me dais solución.La variable fechIni la traigo en String, por eso la he convertido en DateTime.
Map<DateTime, List<dynamic>> _groupEvents(List<Body> events) {
Map<DateTime, List<dynamic>> data = {};
events.forEach((event) {
  DateTime date = DateTime.parse(event.fechaIni);
  if (data[date] == null) data[date] = [];
  data[date].add(event);
});
return data;

}
Gracias de antemanos.

A: Nunca he utilizado Dart pero leyendo la documentacion encontre que DateTime tiene sus metodos .year - .month - .day que obtienes lo que quieres dando una fecha YYY-MM-DD con - y no con /.
Por ello una solucion que le di es reemplazar todos los / por - usando replaceAll de la siguiente manera y probado en dartpad:
var fecha = '2020/12/16';
fecha = fecha.replaceAll('/', '-');

DateTime date = DateTime.parse(fecha);
print(date.year); //Año
print(date.month); //Mes
print(date.day); //Dia

Cabe resaltar que year-month-day devuelven int segun la documentacion
Otra solucion que encontre buscando es en instalar la libreria intl-package  para formatear la fecha y obtener los datos que quieres, de la siguiente manera:
import 'package:intl/intl.dart';

main() {
  final DateTime now = DateTime.now();
  final DateFormat formatter = DateFormat('yyyy');
  final int formatted = formatter.format('2020/12/16');
  print(formatted); // 2013
}

Esto ultimo aun no lo he probado pero si saliera un error, en su documentacion esta mas detallado


text:
Q: open file in ionic app how can i navigate trhoug file in my device and open it in ionic app? I follow this 2 tutorial both work but in the first one i can't open file and i don't know how to insert the second one to open file. Please help
FIRST, SECOND.
My code
 var app=angular.module('starter', ['ionic','ngCordova'])
    .run(function($ionicPlatform) {
      $ionicPlatform.ready(function() {
        if(window.cordova && window.cordova.plugins.Keyboard) {
          // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
          // for form inputs)
          cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

          // Don't remove this line unless you know what you are doing. It stops the viewport
          // from snapping when text inputs are focused. Ionic handles this internally for
          // a much nicer keyboard experience.
          cordova.plugins.Keyboard.disableScroll(true);
        }
        if(window.StatusBar) {
          StatusBar.styleDefault();
        }
      });
    });

    app.controller("ExampleController", function($scope, $cordovaFile, $ionicPlatform, $fileFactory, $cordovaPrinter, $cordovaFileOpener2, $interval, $rootScope) {

      $scope.openPDF= function() {
              $cordovaFileOpener2.open(
                fileSystem.name,
                'application/pdf'
              ).then(function() {
                  console.log('Success');
              }, function(err) {
              console.log('An error occurred: ' + JSON.stringify(err));
              });
          };

      var fs = new $fileFactory();

      $ionicPlatform.ready(function() {
        fs.getEntriesAtRoot().then(function(result) {
          console.log("result "+ JSON.stringify(result));
          $scope.files = result;
        }, function(error) {
          console.error(error);
        });

        $scope.getContents = function(path) {
          fs.getEntries(path).then(function(result) {
            console.log("result "+JSON.stringify(result));
        //    console.log("result "+result);
            $scope.files = result;
            $scope.files.unshift({name: "[parent]"});
            //funzione per trovare il padre del path corrente
            fs.getParentDirectory(path).then(function(result) {
            //  console.log("result "+result);
              console.log("result "+JSON.stringify(result));
              result.name = "[parent]";
              $scope.files[0] = result;
    /*
              $cordovaFileOpener2.open(
              fileSystem.fullPath,
              'application/pdf'
              ).then(function() {
                  console.log('Success');
              }, function(err) {
              console.log('An error occurred: ' + JSON.stringify(err));
              });

                deferred.resolve(entries);
              console.log("entries "+ JSON.stringify(entries));
    */

            });
          }, function(error){
            console.error(error);
          });
        }
      });

    });

    app.factory("$fileFactory", function($q, $cordovaFileOpener2) {

      var File = function() {};

      File.prototype = {

        getParentDirectory: function(path) {
          //questa è la promise
          var deferred = $q.defer();
          //accedo al file local e prendo il path
          window.resolveLocalFileSystemURL(path, function(fileSystem) {
            fileSystem.getParent(function(result) {
              console.log("result "+JSON.stringify(result));
              deferred.resolve(result);
            }, function(error) {
              deferred.reject(error);
            });
          }, function(error) {
            deferred.reject(error);
          });
          return deferred.promise;
        },

        //per trovare tutti i file e cartelle nella root del device
        getEntriesAtRoot: function() {
          var deferred = $q.defer();
          window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
                console.log(fileSystem.name);
            var directoryReader = fileSystem.root.createReader();
            directoryReader.readEntries(function(entries) {
          //    console.log("entries "+entries);
              console.log("result "+ JSON.stringify(entries));
              deferred.resolve(entries);
            }, function(error) {
              deferred.reject(error);
            });
          }, function(error) {
            deferred.reject(error);
          });
          return deferred.promise;
        },

        //per trovare tutti i files e cartelle nel path dato
        getEntries: function(path) {
          var deferred = $q.defer();
          window.resolveLocalFileSystemURL(path, function(fileSystem) {
            console.log(fileSystem.name);
            console.log(fileSystem.fullPath);

            var directoryReader = fileSystem.createReader();
            console.log("directoryReader "+JSON.stringify(directoryReader));
            directoryReader.readEntries(function(entries) {
            //  console.log("entries "+entries);
    /*
            $cordovaFileOpener2.open(
            fileSystem.fullPath,
            'application/pdf'
            ).then(function() {
                console.log('Success');
            }, function(err) {
            console.log('An error occurred: ' + JSON.stringify(err));
            });

              deferred.resolve(entries);
            console.log("entries "+ JSON.stringify(entries));
    */
            }, function(error) {
              deferred.reject(error);
            });

          }, function(error) {
            deferred.reject(error);
          });
          return deferred.promise;
        }

      };

      return File;

    });


text:
Q: Coordinate Vector in Orthonormal Basis Is the following statement correct?

For some vector $\mathbf{v}$ in an inner product space and an orthonormal basis for that space $B=\{ \mathbf{b}_{1},\mathbf{b}_{2},\ldots,\mathbf{b}_{n} \}$, the coordinate vector $[\mathbf{v}]_{B}=\begin{bmatrix}
           \langle\mathbf{v}{,}\;\mathbf{b}_{1}\rangle \\
           \langle\mathbf{v}{,}\;\mathbf{b}_{2}\rangle \\
           \vdots \\
           \langle\mathbf{v}{,}\;\mathbf{b}_{n}\rangle
         \end{bmatrix}$

My text book states this equation: $\mathbf{v}=\langle\mathbf{v}{,}\;\mathbf{b}_{1}\rangle\,\mathbf{b}_{1}+\cdots+\langle\mathbf{v}{,}\;\mathbf{b}_{2}\rangle\,\mathbf{b}_{2}$, but doesn't extend the idea to coordinate vectors. Is my statement correct?


text:
Q: NG SERVE command issue I got problem with running my angular app via ng serve.
After hours and hours of fighting with angular (had many problems with angular cli) I am able to generate project without errors. I imported this project to IntelliJ and want to run  by ng serve command.
after call  ng serve   got this:
The program 'ng' is currently not installed. You can install it by typing:
sudo apt install ng-common
Any ideas?

A: Make sure that you are running the "ng serve" command from inside the root directory of your angular project (the cli path is correct).
This error occurres because your command line interface cannot make sense of the command and whilst "ng new project" may execute from practically anywhere, other ng commands such as "ng serve" can only execute from within the project root directory.

A: Hope this guide will help you to create a project without errors.
1. first open terminal or console window and run, npm install -g @angular/cli
2. To create a new workspace and initial starter app, ng new my-app-name
3. Go to my-app-name folder, cd my-app-name
4. Launch the server by using the CLI command, ng serve --o (--o to open in browser)


text:
Q: REST Request - AWS Access Key ID and AWS Secret Access Key I am reading this document Authenticating Rest Requests
The first paragraph says ..

Every non-anonymous request to S3 must contain authentication information to establish the identity of the principal making the request. In REST, this is done by first putting the headers in a canonical format, then signing the headers using your AWS Secret Access Key.
There are two ways to send your signature with a request. The first is to put your AWS Access Key ID and the signature you computed into the Authorization header.

My 1st question is-
Is AWS Secret Access Key the same as AWS Access Key ID?
if not the same, Where do I get the AWS Secret Access Key and AWS Access Key ID?
My 2nd question is about 'signature you computed'
I understand that this signature is computed like this -
String signatureYouComputed = base64(hmac-sha1(VERB + "\n"
                                 + CONTENT-MD5 + "\n"
                                 + CONTENT-TYPE + "\n"
                                 + DATE + "\n"
                                 + CanonicalizedAmzHeaders + "\n"
                                 + CanonicalizedResource))

Here how do i get CONTENT-MD5, CanonicalizedAmzHeaders, and CanonicalizedResource?
I know these are basic questions for experienced integration developers but not for everyone. Please help me understand.

A: I think this is both an AWS and SF question, but I think I can help. You're trying to Authenticate via HMAC. It depends on the SHA1 Algo and the  Content-MD5 header that is later base64 encoded.

*

*Re: Keys/ Secrets: In AWS, Access keys consist of two parts: an access key ID (for example, AKIAIOSFODNN7EXAMPLE) and a secret access key (for example, wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY). This link will give you the docs on how to get both of them.

*RE: Computing the Signature: This code is pretty much what I use:

@future (callout=true)
public static void sendRequest(String jsonString){
    DateTime dtNow= System.Now();
    String dateFormat= dtNow.format('E, dd MMM yyyy kk:mm:ss z','GMT'); // date format as per the timezone of org
    HttpRequest req = new HttpRequest();
    req.setEndpoint(System.Label.EndPoint); // endpoint URL

    String strMd5= EncodingUtil.base64Encode (Crypto.generateDigest('MD5', Blob.valueOf(jsonString)));
    String strCanonical = 'application/json' + ',' + strMd5 + ',' + request URL + ',' +dateFormat;
    String strSignature = EncodingUtil.base64Encode(generateHmacSHA1Signature(strCanonical, system.label.Secret_Key));
    String authorizationHeader = system.label.APIAuth + ' ' + System.Label.Access_Id + ':' + strSignature;req.setMethod('POST');

    req.setHeader('ACCEPT',System.label.Accept_Header); // accept headers
    req.setHeader('Authorization', authorizationHeader);
    req.setHeader('Content-Type', System.label.Content_Type); // content Type
    req.setHeader('DATE',dateFormat);
    req.setHeader('CONTENT_MD5',strMd5);
    req.setHeader('request_uri',System.Label.EndPoint);
    req.setBody(jsonString);
    Http http = new Http();

    if(!test.isRunningTest()){
        HTTPResponse res = http.send(req);
    }
}

public static blob generateHmacSHA1Signature(String canonical_str, String secreteKey){
    Blob mac = Crypto.generateMac('HMacSHA1', blob.valueof(canonical_str),blob.valueof(secreteKey));
    return mac;
}

I got it from this blog, and they gives some more info https://www.thinqloud.com/hmac-authentication-in-salesforce/


text:
Q: How can I create a dependency graph from a text file? Lets say I have a text file with the following data:
Form1 | L3 | depends on L4 and L5
Form1 | L4 | no dependence
Form1 | L5 | depends on L6
Form1 | L7 | no dependence

What I would like to do is output a directed graph (where direction means "depends on"). In this example, we would have a graph with 2 components, one being a single vertex labelled "L7", and the other being 4 vertices connected in series (a 4-path), with arrows in the obvious directions.
I'm using Python 2.7 on a mac. I'm also very new to programming, but very skilled in mathematics (if that makes a difference).

A: One easy way would be to convert your input text file format to the Graphviz "dot" file format.  Here's an example of someone writing a dot file using Python with no external libraries: How can python write a dot file for GraphViz asking for some edges to be colored red?
And there's PyDot which you could use to do the same thing: https://github.com/erocarrera/pydot
Once you have a "dot" file,  you can  turn it into an actual image using Graphviz (a separate program): http://www.graphviz.org/


text:
Q: While-loop with two values i'm a beginner trying to understand how to write a while loop code that write out numbers in order and how many depends on the loop. For example loop(3,6) results in 3456. This is my try this far
public static void loop(int start, int end){

int loop = 1;
while( loop <= start && end < runLoop ){
     System.out.print( start + end ) ;
loop = loop+1;

   }
}

A: Just use start directly, until it reaches end:
public static void loop(int start, int end){
   while(start <= end){
      System.out.print(start);
      start++;
   }
}


text:
Q: Using strrpos() with PHP
Possible Duplicate:
How to make strpos non case sensitive

I am testing to see if a string contains the text "People Who Like". Well, the code works great! Except it is case-sensitive. What can I do to prevent this?
If the string is "people who like to run" it returns false
If the string is "People who like to run" it returns true
I want it to not be case sensitive.
Code:
<?php

$string = "People who like to run";

if (strrpos($string, 'People who like') === false) {
    echo "False";
}
else {
    echo "True";
}

A: use strripos instead
OR
use strtolower on the string before testing it
$string = "People who like to run";

if (strrpos(strtolower($string), strtolower('People who like')) === false) {
    echo "False";
}
else {
    echo "True";
}

A: Use strripos for case-insensitive match

A: See strripos, the case insensitive-version of strrpos.


text:
Q: Как выводить исключения в файл? можно ли вывести исключения в файл не используя try .. catch?

A: Так лучше не делать.
Однако вот что есть:
https://secure.php.net/manual/ru/function.set-exception-handler.php
Пример из документации:
<?php
function exception_handler($exception) {
  echo "Неперехватываемое исключение: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Неперехватываемое исключение');
echo "Не выполнено\n";
?>


text:
Q: ImageMagick identify not working I am using Debian Buster and trying to use ImageMagick. I have installed ImageMagick on my system by compiling source files as given in this official page. identify -v gives me following,
Version: ImageMagick 7.0.8-53 Q16 x86_64 2019-07-15 https://imagemagick.org
Copyright: © 1999-2019 ImageMagick Studio LLC
License: https://imagemagick.org/script/license.php Features: Cipher DPC HDRI OpenMP(4.5)
Delegates (built-in):

However when I am trying to see metadata of one of the raw file, it is giving me following error
>> identify -verbose _MG_7227.CR2
identify: unable to open image '/tmp/magick-21769M0_HHYUYw2MT.ppm': No such file or directory @ error/blob.c/OpenBlob/3497.

When I used it on some JPG image, I got some different error message
>> identify -verbose IMG_20181226_134152.jpg
identify: no decode delegate for this image format `JPG' @ error/constitute.c/ReadImage/556.

Can anyone tell me what is going on?

A: The
Delegates (built-in):

line in your identify --version output suggests that something went wrong during compilation; I'd expect output more in line with that produced by the packaged version of ImageMagick in Debian:
Delegates (built-in): bzlib djvu fftw fontconfig freetype heic jbig jng jp2 jpeg lcms lqr ltdl lzma openexr pangocairo png tiff webp wmf x xml zlib

If you don't mind having a slightly older version of ImageMagick, 6.9.10 rather than 7.0.8, it's probably simpler for you to use the Debian packages instead:
sudo apt install imagemagick


text:
Q: calling a random integer variable in code (objective-c, xcode) Im trying to write some code where the computer creates a random integer between 1 and 12 and I want to be able to compare that number elsewhere in my code.  How do I call that number in a method? Im very new to this so any help is appreciated
heres how i called it in the .h
int losingVault

in the .m this how i create the random number
losingVault=rand()%12+2;

how do i call that elsewhere in my code?

A: Well, this isn't a lot to go on.  It seems like you may need some basic help understanding Objective-C.  There are a couple books people like to recommend, Programming in Objective-C by Stephen Kochan is probably the most popular.
So, the way your example code is written, losingVault will probably have visibility in the entire class in which it was defined.  If you look in your .h file, int losingVault; is probably within an @interface {ClassName} block.  In your .m file, there should be a matching @implementation {ClassName} block.  Anywhere inside that block should be able to access the variable by just calling losingVault.  You could make that variable visible outside of that class in a number of ways.
I hope this helps.


text:
Q: is it possible to pass dynamic values to the tags of xml file from .properties file I have around 100 plain xml files with repetetive static values. I would like to change them into dynamic by getting values from .properties file so that i can change that value in one place. Is it possible??
Example of current xmls I have :
<?xml version="1.0"?>
<bookstore>
  <book category="children">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
</bookstore>

**desired change:**

**prop.properties.com**
bookName=Harry Potter
authorName=J K. Rowling
yearValue=2005
priceValue=29.99

<?xml version="1.0"?>
<bookstore>`enter code here`

//load properies file

  <book category="children">
    <title>${bookName}</title>
    <author>${authorName}</author>
    <year>${yearValue}</year>
    <price>${priceValue}</price>
  </book>
</bookstore>


text:
Q: How to pass table name as a parameter to cursor with out creating view in a dynamic way I am trying to delete the records with the break-even commits.
I am passing the table name, date and cleanup frequency as the parameters to the procedure. As we need to have break-even commits, I am using the cursor however cursor is not allowing to take the table name as a parameter.
Can I have leads if any below is the code that I developed?
CREATE PROCEDURE `sp_datacleanup_test`(IN tab_name VARCHAR(50),
                            IN modified_date VARCHAR(20),
                            IN cleanup_window VARCHAR(30),
                            OUT recordsProcessed INT)
BEGIN

    DECLARE No_More_Rows INT DEFAULT FALSE;
    DECLARE modified_dt varchar(50);
    DECLARE v_counter INT;
    DECLARE stmt varchar (500);
    DECLARE rowsdeleted INT DEFAULT 0;
    DECLARE counter INT DEFAULT 0;

    BEGIN
    DECLARE Sel_cur CURSOR for select cast(modified_dateas char) as modified_dt,count(1) as counter from tab_name where status_flag = 'D' and modified_date <= cleanup_window group by modified_date;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET No_More_Rows = TRUE;

        OPEN Sel_cur;
        READ_LOOP:LOOP

            FETCH Sel_cur INTO modified_dt,v_counter;

                IF No_More_Rows THEN
                    LEAVE READ_LOOP;
                END IF;

                SELECT modified_dt,v_counter;

                set @delstm = concat('delete from ', tab_name,' where ', modified_date,' = ''',modified_dt,'''
                            and status_flag = ''D''');

                PREPARE stmt FROM @delstm;
                EXECUTE stmt;
                DEALLOCATE PREPARE stmt;

                set counter = counter + v_counter;

                select counter;

                    IF counter = 10000 THEN
                        COMMIT;
                        set counter = 0;
                    END IF;

                set rowsdeleted = rowsdeleted + counter;

                select rowsdeleted;

                set recordsProcessed = rowsdeleted;

        END LOOP;
        CLOSE Sel_cur;

    END;

COMMIT;

END;

DO we have any other way to achieve this with out using Create view?
Thanks


text:
Q: Navigation bar floats when filling out form on a smartphone I have a fixed nav bar which works perfectly on the desktop, responsinator, etc.  When I attempt to fill out a form field on my iPhone, the navigation bar mysteriously floats; when I scroll up or down it stays in the middle of the screen.

Any help would be greatly appreciated.  My code is available here and on jsFiddle.

    $(function () {
    var pull = $('#pull');
    menu = $('nav ul');
    menuHeight = menu.height();

    $(pull).on('click', function (e) {
        e.preventDefault();
        menu.slideToggle();
    });

    $('nav li>a').on('click', function (e) {
        if ($(window).width() < 600) {
            menu.slideUp();
        }
    });

    $(window).resize(function () {
        var w = $(window).width();
        if (w > 320 && menu.is(':hidden')) {
            menu.removeAttr('style');
        }
    });
    });
/* Clearfix */

.clearfix:before, .clearfix:after {

    content:" ";

    display: table;

}

.clearfix:after {

    clear: both;

}

.clearfix {

    *zoom: 1;

}

/* Basic Styles */

nav {

    height:42px;

    top: 0;

    position: fixed;

    border-bottom: 2px solid #e1e1e1;

    width: 100%;

    margin: 0px auto;

    background: #e63333;

    font-size: 105%;

    font-weight: 400;

    text-align: center;

    z-index:99;

}

nav ul {

    padding: 2px;

    margin: 0 auto;

    width: auto;

    height: 40px;

}

nav li {

    display: inline;

    float: none;

}

nav a {

    color: #fff;

    display: inline-block;

    width: 80px;

    text-decoration: none;

    line-height: 40px;

}

nav li:last-child a {

    border-right: 0;

}

nav a:hover, nav a:active {

    background-color: #f95f5f;

}

nav a#pull {

    display: none;

}

/*Styles for screen 600px and lower*/

@media screen and (max-width: 600px) {

    nav {

        height:auto;

        top: 0;

        background-color:#e35f5f;

    }

    nav ul {

        width: 100%;

        display: block;

        height: auto;

    }

    nav li {

        width: 50%;

        float: left;

        position: relative;

    }

    nav li a {

    }

    nav a {

        text-align: left;

        width: 100%;

        text-indent: 25px;

    }

}

/*Styles for screen 515px and lower*/

@media only screen and (max-width: 600px) {

    nav {

        border-bottom: 0;

        background-color:#e35f5f;

    }

    nav ul {

        display: none;

        height: auto;

    }

    nav a#pull {

        display: block;

        background-color: #e63333;

        width: 100%;

        position: relative;

        box-shadow: 2px 2px 0px #888888;

    }

    nav a#pull:after {

        content:"";

        background: url('../images/nav-icon.png') no-repeat;

        width: 30px;

        height: 30px;

        display: inline-block;

        position: absolute;

        right: 15px;

        top: 10px;

    }

}

/*Smartphone*/

@media only screen and (max-width: 320px) {

    nav li {

        width: 50%;

        float: left;

    }

    nav li a {

        border-bottom: 1px solid #576979;

    }

}

/* End Clearfix */

/* Chef Registration Form */

:-moz-placeholder {

    font-size: 105%;

    font-weight: 400;

}

::-webkit-input-placeholder {

    font-size: 105%;

    font-weight: 400;

}

*:focus {

    outline: none;

}

.form {

    margin: 10px auto;

    width:60.5%;

    height:auto;

    background-color: #e6e6e6;

    border: 1px solid #b9afaf;

    text-decoration: none;

    border-radius: 5px;

    -webkit-border-radius: 5px;

    -moz-border-radius: 5px;

    -ms-border-radius: 5px;

    -o-border-radius: 5px;

    padding-left: 2.5%;

    padding-top: 20px;

}

.form input {

    width: 90%;

    padding: 8px 0 8px 8px;

    margin-left: 12px;

    list-style-type: none;

    border-radius: 5px;

    -webkit-border-radius: 5px;

    -moz-border-radius: 5px;

    -ms-border-radius: 5px;

    -o-border-radius: 5px;

    border: 1px solid #ccccff;

    background: #fafafa;

}

.form button {

    width: 91%;

    margin-bottom: 8px;

    margin-left: 15px;

}

.form li {

    padding-bottom:8px;

    position:relative;

    list-style-type: none;

}

.form textarea {

    max-width: 90%;

    min-width: 90%;

    padding: 4px 0 4px 8px;

    margin-left: 12px;

}

.form input, .form textarea {

    border:1px solid #aaa;

    box-shadow: 0px 0px 3px #ccc, 0 10px 15px #fafafa inset;

}

.form input:focus, .form textarea:focus {

    background: #fff;

    border:1px solid #6699ff;

    box-shadow: 0 0 3px #aaa;

    list-style-type: none;

}

/* Button Style */

button.submit {

    background-color: #e63333;

    background: -webkit-gradient(linear, left top, left bottom,    from(#e43535), to(#e63333));

    background: -webkit-linear-gradient(top, #e43535, #e63333);

    background: -moz-linear-gradient(top, #e43535, #e63333);

    background: -ms-linear-gradient(top, #e43535, #e63333);

    background: -o-linear-gradient(top, #e43535, #e63333);

    background: linear-gradient(top, #e43535, #e63333);

    border: 1px solid #888888;

    border-bottom: 1px solid #888888;

    border-radius: 5px;

    -webkit-border-radius: 5px;

    -moz-border-radius: 5px;

    -ms-border-radius: 5px;

    -o-border-radius: 5px;

    box-shadow: inset 0 1px 0 0 #888888;

    -webkit-box-shadow: 0 1px 0 0 #888888 inset;

    -moz-box-shadow: 0 1px 0 0 #888888 inset;

    -ms-box-shadow: 0 1px 0 0 #888888 inset;

    -o-box-shadow: 0 1px 0 0 #888888 inset;

    color: white;

    font-weight: 400;

    font-size: 105%;

    padding: 6px 20px;

    text-align: center;

}

button.submit:hover {

    opacity:.85;

    cursor: pointer;

}

button.submit:active {

    border: 1px solid #303030;

    box-shadow: 0 0 5px 5px #888888 inset;

    -webkit-box-shadow:0 0 5px 2px #888888 inset;

    -moz-box-shadow: 0 0 5px 2px #888888 inset;

    -ms-box-shadow: 0 0 5px 2px #888888 inset;

    -o-box-shadow: 0 0 5px 2px #888888 inset;

}

/* End of Chef Registration Form */

Home

Rates

Pay

Buyout

Join

Contact

 Menu

A: don't use the position: fixed; use position: absolute; instead.
nav {
        height:42px;
        position: absolute;
        top: 0;
        border-bottom: 2px solid #e1e1e1;
        width: 100%;
        margin: 0px auto;
        background: #e63333;
        font-size: 105%;
        font-weight: 400;
        text-align: center;
        z-index:99;

    }