text:
Q: Any way to use the C# compiler object (CSharpCodeProvider) to build "inline"? I use the CSharpCodeProvider to build dynamic C# and it works great. Slightly faster then expression trees and certainly easier to maintain over expression trees and IL...
I've run into a case where it doesn't seem like its going to work.
ConsoleApp1.exe
  MyClass
I then use CSharpCodeProvider to generate an in memory temp DLL. Say, something basic like this:
void TestFunc(MyClass input)
{
}
This generates a compiler error because the CSharpCodeProvider doesn't have a reference to MyClass. Since MyClass lives in an EXE, adding a reference to the compiler object doesn't work. I get an error saying it can't find the metadata for ConsoleApp1.
Is there anyway to make the code live in the context of the EXE? Or is there some way to make the reference work? I know it works if I move MyClass to a DLL and then add that as a reference, but that's an unacceptable requirement for users of my class.
EDIT:
So, using pure expression trees, I generate this method:
.Lambda #Lambda1<System.Func`2[ConsoleApplication2.Source,ConsoleApplication2.Dest]>(ConsoleApplication2.Source $var1) {
    .New ConsoleApplication2.Dest(){
        S1 = .Call $var1.get_S1(),
        S2 = .Call $var1.get_S2(),
        I1 = .Call $var1.get_I1(),
        I2 = .Call $var1.get_I2(),
        S3 = .Call $var1.get_S3(),
        S4 = .Call $var1.get_S4(),
        S5 = .Call $var1.get_S5()
    }
}

compiled to a lambda, calling it 1M times takes ~285ms.
The "compiler" way, I generate this code:
namespace ConsoleApplication2
{
    public class TestClass
    {
        public static ConsoleApplication2.Dest TestFunc(ConsoleApplication2.Source source)
        {
            ConsoleApplication2.Dest d = new ConsoleApplication2.Dest();

            d.S1 = source.S1;
            d.S2 = source.S2;
            d.I1 = source.I1;
            d.I2 = source.I2;
            d.S3 = source.S3;
            d.S4 = source.S4;
            d.S5 = source.S5;

            return d;
        }
    }
}

Then I build a typed lambda off of that:
    ParameterExpression p1 = Expression.Parameter(typeof(Source));
    var v = Expression.Lambda<Func<Source, Dest>>(Expression.Call(mi, p1), new ParameterExpression[] { p1 }).Compile();

When I call v(obj) 1M times, it only takes 133ms 1/2 the time of the pure expression tree.
I'm just hesitant to go this route due to the requirement of the classes having to be public in the EXE or even in a DLL.
Any idea why the expression tree is so much slower?

A:
Is there anyway to make the code live in the context of the EXE?

No. The CSharpCodeProvider creates an assembly at runtime, so there's no way to "inject" that into the currently running assembly, which is a compiled assembly at that point.

is there some way to make the reference work?

You answered this question yourself - add the EXE extension to the reference name so it knows to load an EXE rather than a DLL.


text:
Q: pygame loaded image used in tkinter "doesn't exist" First of all I'm fairly new with Python and I acknowledge that my code is unorganized. Relating to the actual question though, basically I loaded an image to a variable using pygame. I am using that image in a toplevel in tkinter. When I attempt to use the image in a label on that toplevel, it says that it doesn't exist. I'm using a module that I created in some areas, but I don't think it would have any relation, so I'm not including it.
import tkinter as tk
from myfunctions import *
import pygame

master = tk.Tk()
master.resizable(0,0)

info = "Guess a number between \n 1 and 99 inclusive!"

f=tk.Frame(master, width=500, height=450)
f.pack_propagate(0)
f.pack()

l=tk.Label(f, text=info, font=("Arial", 30))
l.pack()

heat=tk.Label(f, font=("Arial", 24), fg="red", pady=30)
heat.pack()

f2= tk.Frame(f)
f2.pack()

spinbox = tk.Spinbox(f2, from_= 1, to = 99)
spinbox.pack()

bframe=tk.Frame(f, pady =30)
bframe.pack()

def itsago():
    valid = validcheck(spinbox.get())
    if valid == 0:
        heat.config(text="Not a valid input")
        heat.pack()
    else:
        hcheck = hiddencheck(valid)
        heat.config(text=hcheck)
        heat.pack()
        if hcheck == "You won!\n Re-Open the program to play again.":
            pwin= tk.Toplevel()
            pwin.resizable(0, 0)
            sloth = pygame.image.load('paradesloth.png')
            lparade = tk.Label(pwin, anchor = "nw")
            lparade.config(image = sloth)
            lparade.image = sloth
            lparade.pack()
            pwin.mainloop()

b = tk.Button(bframe, command = itsago, text="Check Number", font=("Arial", 20),       bg="white")
b.pack()

master.mainloop()

Any help would be greatly appreciated :)
*EDIT: forgot to add one of the most important things, the error:
File "C:\Python33\lib\tkinter\__init__.py", line 1254, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "<Surface(800x599x24 SW)>" doesn't exist

A: Answered by martineau in the comments:

pygame.image.load() returns a pygame.surface object, which is not the same thing as a tk.PhotoImage object -- they're not interchangeable. – martineau 8 mins ago

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cakephp copy value from other model to main model Hi I have model Product and few relative models, output array:
array (size=2)
  0 =>
    array (size=6)
      'Product' =>
        array (size=7)
          'id' => string '121' (length=3)
          'code' => string '123' (length=3)
      'ProductLanguage' =>
        array (size=7)
          'id' => string '5' (length=1)
          'product_id' => string '121' (length=3)
          'name' => string 'abc' (length=3)
      'ProductPrice' =>
        array (size=2)
          0 =>
            array (size=9)
           'id' => string '1' (length=1)
           'product_id' => string '121' (length=3)
           'type_id' =>  string '7'
           'price' => string '555' (length=3)

          1 =>
            array (size=9)
           'id' => string '2' (length=1)
           'product_id' => string '121' (length=3)
           'type_id' =>  string '8'
           'price' => string '900' (length=3)
   1 =>
...

Is it possible copy price from first record (record 0 from ProductPrice>price) to Product?
I want this:
array (size=2)
  0 =>
    array (size=6)
      'Product' =>
        array (size=7)
          'id' => string '121' (length=3)
          'code' => string '123' (length=3)
          'price' => 555
....

A: Yes, in your afterFind callback (In Product Model)
public function afterFind($results, $primary = false) {
    foreach ($results as $key => $val) {
        if (isset($val['ProductPrice'][0]['price'])) {
            $results[$key]['Product']['price'] = $val['ProductPrice'][0]['price'];
        }
    }
    return $results;
}


text:
Q: PostgreSQL: Getting Strings between double Brackets I am new to PostgreSQL and decided to play around with it a little bit. Thus I want to extract Strings from a Marked-Up text, but I do not get the result I wanted.
To do that I have a simple table named book and a column with a text data type called page.
The data looks something like this:
Simon the Sorcerer is a [[teenager]] transported into a fantasy world as a
[[Sorcerer (person)|sorcerer]] dressed in a cloak and [[pointy hat]]; his
cloak and hat are purple in the first game, but change to red for the rest
of the series (aside from possible magical colour changes in the third game).
He must use his logic and magical skills to solve puzzles as he progresses
through the games.

Now I want to extract each String between the brackets [[ ]]. But how do I do that correctly? Or is that even possible without Plug-ins?
I tried different versions with LIKE which did not produce any results, e.g.:
SELECT * FROM book WHERE page LIKE '[[%]]';
SELECT * FROM book WHERE page LIKE '[[teenager]]';
...

I also played a bit with regex, but I only got the whole dataset back instead of the String between the brackets:
SELECT * from book where page ~ '[^[[]+(?=\]])';

Is there a solution for my problem? Help will be much appreciated!

A: Use the regexp_matches function:
select regexp_matches(page,'[^[[]+(?=\]])','g') from book


text:
Q: Describe curves by words I am trying to describe the general aspect of the following curves
My ideas:

*

*The curves are continuous, and defined for positive values of x, and giving negative values.

*Have logarithmic growth (increase logarithmically)

*The curves become flatten as they approaches the x axis.

Does any one have other ideas for  describing such curves?
Please feel free to point me if the ideas I mentioned are not suitable for describing the curves.
Thank you in advance.


text:
Q: c++ assembley inline codes error I have written some assembly in-line  codes like the codes below:
void write_sb(BYTE bIdx, DWORD dwVal){
_asm {
    mov dx, 0x0cf8
    mov eax, 0x80003800
    mov al, bIdx
    out dx, eax
    mov dx, 0x0cfc
    mov eax, dwVal
    out dx, eax
}
}

running the function make  0xC0000096: Privileged exception. not only this function but all assembly inline codes throw exceptions and I don't know what to do with it! some searches told me about running my codes in kernel mode. I did not find how can I run assembly in-line codes in kernel mode or how to fix in another way. any suggestion?

A: the link helped me out!
https://social.msdn.microsoft.com/Forums/en-US/0e10813e-9813-4e84-89f9-845eaa941c27/c-assembley-inline-codes-error?forum=vcgeneral
we need to write kMDF driver.


text:
Q: error about get data i have a function :
def tong_thoigian (self,cr,uid,ids,context={}):
                obj=self.browse(cr,uid,ids,context=context)[0]
                cr.execute('''select name,giolam from x_giolam where name=%s'''%(obj.ma_luong))
                kq=cr.fetchall()
                tong=0.00000
                for i in kq:
                      tong+=kq[1]
                self.write(cr,uid,ids,{'tonggiolam':tong},context=context)

and this is table x_giolam:
class x_giolam(osv.osv):
    _name = 'x_giolam'
    _description = 'Gio Lam'
    _columns = {
                        'name': fields.integer('Lọai',size=64,required="true"),
                        'giolam' : fields.float('Gio lam',size=64,required="True"),
                        'time_in': fields.char('Gio vào',size=20),
                        'time_out' :fields.char('Gio về',size=20),
                        'congviec' :fields.char('Cong viec',size=50),
    }
x_giolam()

and the 'self' is table x_salary, i think isn't importance to say about it because i want write a function for sum salary of a staff when name=Ma_luong of table x_salary
and the error is
IndexError: list index out of range

the type of Giolam is float...
and i write with in openerp
and i think error in line 'tong+=kq[1]'
How can i fix it  ?
thanks!!

A: Using my magic crystal ball, I'm guessing that cr.execute is a call to the standard database API. So kr.fetchall() will return a tuple of rows. However, it seems that your SQL is returning only a single row.
You probably mean tong += kq[0][1], ie the second column (giolam) of the first row of the result. Alternatively, use kr.fetchone() to just get a single row, then you can keep it as kq[1]. Either way, you should check that your db call actually returns results.


text:
Q: Code returning NAN I wrote some javascript in hopes of outputting time as hh:mm  (EG: 15:45)
However my code is returning Nan:Nan
var timer = 24;
var time1 = new Date();
time1.setHours(time1.getHours + (6));
time1.setMinutes(time1.getMinutes());
document.write(time1.toString("hh:mm"));

Can someone help me understand why this isn't working as intended?

A: The getHours member is a function not a value.  Hence you're multiplying a number by a method and getting NaN.  Make sure to invoke the method
time1.setHours(time1.getHours() + (6));

A: The problem is that time1.getHours is a method. When you add 6 to a method, the result is NaN. You need to actually call it:
time1.setHours(time.getHours() + 6);

A: you can use document.write(time1.getHours()+":"+time1.getMinutes()); instead of it.


text:
Q: Twitter bootstrap nav-stacked css not working I am trying to achieve the stackable effect as shown here:
http://twitter.github.com/bootstrap/components.html#navs
but somehow it is not working for me. Here is the link to a plunk that I have created:
http://plnkr.co/edit/LSR3ijKGiOIyrYAbHm7g
It just shows three list items one below another without the navbar effect of bootstrap.
<!doctype html>

    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">

 Item1

 Item2

 Item3

I must be doing some blunder that something as simple as nav-stacked is not working. Would be glad and grateful if someone could point out my mistake.

A: Put the content in anchors, like so:

Item1

Item2

Item3

Demo: http://jsfiddle.net/jpKAF/


text:
Q: Mariadb: assignment operator (:=) not working with local variables The Mariadb Knowledge base explains that the assignment operator (:=) works with both user-defined variables and local variables.
But when I make some tests, for example :
delimiter //
CREATE or replace PROCEDURE tst_PS_now()
BEGIN
declare varnow datetime(3);
set varnow = (select now());
select 'result: ' ,varnow;
END;
//
delimiter ;

mysql:root>  call tst_PS_now() ;
+----------+-------------------------+
| result:  | varnow                  |
+----------+-------------------------+
| result:  | 2020-10-26 16:13:44.000 |
+----------+-------------------------+

example 2:
delimiter //
CREATE or replace PROCEDURE tst_PS_now()
BEGIN
declare varnow datetime(3);
select varnow:=now();
select 'result: ' ,varnow;
END;
//
delimiter ;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':=now();  at line 4

In the second example, the assignment should work with my local variable.
I really need this kind of assignment in my stored procedures.
How may I fix it ? Any idea?


text:
Q: Is in C++ possible create generic function like read()? I have one question (Which is in title too): Is in C++ possible create generic function like read<type>()?
I already tried it by:
template <typename T>
T read() {
    T res;

    if (typeid(T) == typeid(int))
    {
        // some stuff
    }
    else if (/*some other type check*/) {} // etc.
}

And when i tried to compile this, it threw: Invalid conversion from **** to ****. I know why it is throwing exception like this, but is it possible to do that in C++?
Thanks

A: You can achieve something like this. The easiest way is probably to use an explicit specialization:
template <typename T>
T read() {
    T res;

    // etc.
}

template <>
int read<int>() {
    int res;

    // your special int code
}

Depending on what you want to do you may need to use tag dispatch instead.
Note that you should only do this if you can come up with reasonable behavior for the default "unknown T" case. If you only ever want the user to pick one if your predefined special values of T then you should just have separate functions and not use templates here.

A: With templates is possible to do metaprogramming and abstract the actual type to a generic type T, is also possible to

*

*overload a template so the type deduction system will pick the overloaded version instead of the "generic" version

*use the SFINAE technique to pick a given implementation when some conditions are verified

*assertions

*in C++11 environments is also possible to use type_traits
remember that templates are here to leverage you from writing the same implementation for a given function for every type that you use, it's a compile-time feature, after the compilation templates are translated into functions.
If you need to specify a given behaviour based on the type that you got in input, you maybe interested in SFINAE, type_traits, or other similar solution.
You can also template "quantities", numbers, for example you can template an int.
Beware of the fact that templates do not impose a particular "filter" on the type like a check of the signature that a function performs, you can literally throw any type or class to a template, this is one drawback of the templates that you need to handle almost everytime you are using a template.


text:
Q: Filter elements that has ul not only with specific children How do I write jQuery selector to test if li has ul that has at least one li that is not .disabled (may be other classes or without class at all).
Yes sounds complex but it's simple - I need to know if there're uls that do not have "disabled" class on inner lis.
Something like
$("li").filter("*:has(ul:has(li:not(.disabled)))")

A: You can shorten it a bit, like this:
$("li").filter(":has(ul li:not(.disabled))")

You can try it here.  Since the <li> is a child of <ul> you can just refer to it that way, no need for the extra :has() selector confusing Sizzle (multiple :not() in a chain do this as well).
Unless there's the possibility of a <ol> you could remote the ul part as well, just having:
$("li").filter(":has(li:not(.disabled))")


text:
Q: Nestjs how to clear ( reset ) all cache I'm building an API and the data get updated every day at 3 am and need to clear all cached endpoints whatever is!
I'm using the CacheModule and the decorator @UserInterceptor(CacheInterceptor) to cache whatever I need in the controller.
there a Cron function that runs every day at 3 am to update the content, I need to know what the code should put in that method to clear all cache.

A: You can inject the underlying cache manager instance:
constructor(@Inject(CACHE_MANAGER) protected readonly cacheManager) {}

And then use it to delete the caches for all keys:
const keys = await this.cacheManager.keys()
await this.cacheManager.del(keys)

A: According to the official NestJs docs (July 2022), they offer a .reset() method to "clear the entire cache". This examples assumes you're using the naming convention in their docs, where cacheManager is the locally scoped & injected CACHE_MANAGER from @nestjs/common and "Cache" from cache-manager package.
// inside the class constructor
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
// and then inside a class method
await this.cacheManager.reset();

Reference: https://docs.nestjs.com/techniques/caching


text:
Q: ptrace PTRACE_ATTACH failure - Linux permissions of user owned process Why do I need to run as root (not r00t_)?
// main()
scan.scanProcessOffset(10838, 0x7f8c14000000); // proper pid and offset

void MemoryMapper::scanProcessOffset(unsigned int procId, unsigned long long offset)
{
    long attach = ptrace(PTRACE_ATTACH, procId, NULL, NULL);
    cout << attach << endl << errno << endl;

    long memory = ptrace(PTRACE_PEEKDATA, procId, offset);
    if (memory == -1 && errno == 3)
    {
        cout << errno << endl;
        errno = 0;
    }

    cout << memory;
}

As you can see the process I'm hooking into is owned by r00t_
r00t_@:/proc/10838$ ls -l
lrwxrwxrwx 1 r00t r00t_ 0 2012-04-15 08:21 exe -> /usr/bin/gedit
-rw------- 1 r00t r00t_ 0 2012-04-15 09:04 mem

Output not running as root:
r00t_@:~/memedit$ ./a.out
-1
1
3
-1

Output as root:
r00t_@:~/memedit$ sudo ./a.out
0
0
140239607693344

why cant I attach when I am the owner of the process I'm trying to attach to?

A: While some applications use prctl() to specifically disallow PTRACE_ATTACH (e.g. ssh-agent), a more general solution implemented in Yama is to only allow ptrace directly from a parent to a child process (i.e. direct gdb and strace still work), or as the root user (i.e. gdb BIN PID, and strace -p PID still work as root).
In the event of a local app compromise, the attacker is then not able to attach to other processes and inspect their memory and running state.
This behaviour is controlled via the /proc/sys/kernel/yama/ptrace_scope sysctl value. The default is "1" to block non-child ptrace calls. A value of "0" restores the more permissive behaviour, which may be more appropriate for development systems and/or servers with only administrative accounts. Using sudo can also temporarily grant ptrace permissions via the CAP_SYS_PTRACE capability, though this method allows the ptrace of any process.


text:
Q: entity relationship for artist album tracks We have 3 tables:
1. Artist
2. Album
3. Tracks
Artist have one or more albums.
Artist can have mores tracks.
Each album have many tracks.
Now, what if a song doesn't belong to any album and It is a single song from an artist. So how to do the entry? and what should we do with the FOREIGN KEY album_id in Track table. Can it be null?

A: You have 3 tables which represent entity relations. These will associate your entity sets with their attributes. The relationships between your entity sets aren't clearly defined. Each Artist can have many Albums, but how many Artists can each Album have? Each Artist can have many Tracks, but how many Artists can each Track have? Each Album can have many Tracks, but how many Albums can each Track belong to?
In the real world, a song can appear on many albums but each track / appearance of a song might be viewed as a distinct entity. I'm going to assume that a Track can have many Artists, but that a Track belongs to only one Album. In addition, I'll assume we don't need to model the association between Albums and Artists directly, instead we can use the union of the Artists associated with the Tracks on each album, which can be obtained easily enough via a suitable query.

This requires two relationship relations:
TrackArtist (TrackID PK/FK, ArtistID PK/FK)
TrackAlbum (TrackID PK/FK, AlbumID FK)

The relationship between Track and Album can be denormalized into the Track entity relation/table, as a nullable AlbumID column if you want to allow Tracks to exist independent of Albums.
If you want different cardinalities for the relationships, the result will look somewhat different. If you want to record a relationship between Albums and Artists directly, things look much different and you may have to think about consistency between TrackArtist and AlbumArtist.

A: When using a star schema (dimension and fact tables), you could have a fact table with a grain of "track". So each row would be one track. If the track doesn't have an album, then the foreign key for album would be set to 0.
The album table would have a row containing the 0 key, with a description of "not available" or a dash ('-') or whatever makes sense for your reporting purposes.
You could have it null, but if you are doing a count of tracks,and are joining to artists, the row wouldn't return depending on how you write the query.
example query:
select t.track_id, t.track_name, a.album_id, a.album_name, art.artist_id,art.artist_name
from FACT_MUSIC_DB F
JOIN DIM_TRACKS T ON T.TRACK_ID = F.TRACK_ID
JOIN DIM_ALBUMS A ON A.ALBUM_ID = F.ALBUM_ID
JOIN DIM_ARTISTS ART ON ART.ARTIST_ID = F.ARTIST_ID

Table setup example

A: I suggest making a new table ... songs and making the tracks table a link table with foreign keys for albums and songs. Having nulls in a foreign key breaks what a foreign key is designed for.  See https://en.wikipedia.org/wiki/Foreign_key for more details.