text:
Q: Optimization issues with 2D sandbox terrain generation My game:

Each block has a class that doesn't run anything on update, and there is a 200 x 10 span of blocks. I'm implementing random terrain generation later, and this is what I want to be done.
BLOCK CODE: (in every single block, should I optimize? or do it differently?)
using UnityEngine;
using System.Collections;

public class scr_blockMechanics : MonoBehaviour {
//#EDITABLE VARS
    public string block_blockType;
    private SpriteRenderer spriteRenderer;

    public bool isMineable { get; set; }
    public bool isRandomlyGenerated { get; set; }
    public bool isWall { get; set; }
//#STATIC VARS
    GameObject obj_blockItem;
//#START
    void Start () {
        obj_blockItem = GameObject.Find("main_blockItem");
        spriteRenderer = GetComponent<SpriteRenderer>();

        if(isRandomlyGenerated == false){
            isMineable = false;
        }
//#CREATING WALLS
        /*if(isRandomlyGenerated == true && isWall == false){
            //#TODO Create walls!
            GameObject obj_blockWall = (GameObject)Instantiate(gameObject, transform.localPosition, Quaternion.identity);
            obj_blockWall.name = obj_blockWall.name + " WALL";
            obj_blockWall.transform.localPosition = new Vector3(
                obj_blockWall.transform.localPosition.x,
                obj_blockWall.transform.localPosition.y,
                5);

            Collider2D obj_blockWall_collider = obj_blockWall.GetComponent<Collider2D>();
            obj_blockWall_collider.enabled = false;

            Color obj_blockWall_color = Color.grey;//new Vector4(64, 64, 64, 1);

            SpriteRenderer spriteRenderer_wall = obj_blockWall.GetComponent<SpriteRenderer>();
            spriteRenderer_wall.color = obj_blockWall_color;

            scr_blockMechanics blockMechanics_wall = obj_blockWall.GetComponent<scr_blockMechanics>();
            blockMechanics_wall.isRandomlyGenerated = true;
            blockMechanics_wall.isMineable = false; //#TODO: not yet mineable, because it's a wall.
            blockMechanics_wall.isWall = true;

            obj_blockWall.name = blockMechanics_wall.block_blockType+" WALL";
        }*/
    }
//#CREATE ITEM
    void createItem(int uid){
        GameObject obj_blockItemNew = (GameObject)Instantiate(obj_blockItem, transform.localPosition, Quaternion.identity);
        obj_blockItemNew.rigidbody2D.isKinematic = false;
        obj_blockItemNew.name = gameObject.name + " ITEM";
    }
//#DESTROY BLOCK
    void destroyBlock(){
        //print ("'"+transform.name+"' has been destroyed!");
        //spriteRenderer.color = Color.red;
        createItem(0);
        Destroy(transform.gameObject);
    }
//#UPDATE
    void Update () {
        if(renderer.IsVisibleFrom(Camera.main) == true){
            renderer.enabled = true;//gameObject.SetActive(true);
        }

        if(renderer.IsVisibleFrom(Camera.main) == false){
            renderer.enabled = false;
        }
    }

}

'RANDOM' TERRAIN GENERATION
using UnityEngine;
using System.Collections;

public class scr_randomGen : MonoBehaviour {

    private SpriteRenderer spriteRenderer;
    private string[] block_blockTypes = new string[]{
        "DIRT",        //#UID 0
        "STONE",       //#UID 1
        "STONE_BRICK", //#UID 2
    };

    void GENERATE(){
        //#DEFAULTS
        GameObject obj_block = GameObject.Find("main_block");
        int pos_startingPosX = -100;
        int pos_endingPosX = 100;

        int pos_startingPosY = 0;
        int pos_endingPosY = 10;

        float X = 0;
        float Y = 0;
        //#TERRAIN GENERATION
        for(X=pos_startingPosX;X<pos_endingPosX;X=X+1){
            GameObject obj_blockNew = (GameObject)Instantiate(obj_block, new Vector3(0 + (1*X),0,0), Quaternion.identity);
            scr_blockMechanics blockMechanics = obj_blockNew.GetComponent<scr_blockMechanics>();

            blockMechanics.isMineable = true;
            blockMechanics.isRandomlyGenerated = true;
            blockMechanics.block_blockType = block_blockTypes[2];

            obj_blockNew.name = blockMechanics.block_blockType+" "+X+", "+Y;

            for(Y=pos_startingPosY;Y<pos_endingPosY;Y=Y+1){
                obj_blockNew = (GameObject)Instantiate(obj_block, new Vector3(X,1 + (1*Y),0), Quaternion.identity);
                blockMechanics = obj_blockNew.GetComponent<scr_blockMechanics>();

                blockMechanics.isMineable = true;
                blockMechanics.isRandomlyGenerated = true;
                blockMechanics.block_blockType = block_blockTypes[2];

                obj_blockNew.name = blockMechanics.block_blockType+" "+X+", "+Y;
            }
        }
    }

    void Start () {
        GENERATE();
    }

    void Update () {

    }
}

I have it so that if the camera isn't looking at blocks it disables their sprite renderer so it's not rendering as much.
Should I just disable them as a whole? I get 6fps upon running the game.
When I only have, say, 10 - 20 blocks instead of 2000 I get 130 FPS (which is still low in my opinion)
What's the best way to optimize this? make it so I get atleast 70 fps? I wanted to use Java but I don't feel comfortable with the editor and I already put 2 hours of work into this.
I have looked at people's projects in Java and it's a lot smoother and they don't have to worry about the lag. And I have looked at peoples posts saying that it is possible to create a Terarria-like game in Unity but it's always going to be laggy.
Anybody got a good idea on how to fix the lag issues?


text:
Q: SmartThreadPool - Is it possible to pass delegate method with method parameters? I have a long running process called ImportProductInformation called by a consoleapp that I'm trying to speed up, which appears to be an excellent candidate for thread-pooling, so I did a little searching and came across SmartThreadPool on CodeProject and am trying to implement it.
ImportProductInformation currently requires an "item", which is just a single entity-framework row pulled from a list.  SmartThreadPool uses a delegate called "WorkItemCallback", but if I build it like below it complains about "Method name expected" in the foreach loop on smartThreadPool.QueueWorkItem, as it appears I can't pass my params to the delegated method.  What am I missing here?  I'm sure it's something stupid...noob lacking experience with delegates...any help would be appreciated:
    public static void ImportProductInformation_Exec()
    {
        // List
        List<productinformation> _list = GetProductInformation();

        // Import
        if (_list != null)
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            foreach (var item in _list)
            {
                smartThreadPool.QueueWorkItem
                  (new WorkItemCallback
                    (ImportProductInformation(item)));
            }

            smartThreadPool.WaitForIdle();
            smartThreadPool.Shutdown();
        }
    }

    public void ImportProductInformation(productinformation item)
    {
        // Do work associated with "item" here
    }

If I change the loop to this I get "Method is used like a Type" in the build error:
            foreach (var item in _list)
            {
                ImportProductInformation ipi =
                  new ImportProductInformation(item);

                smartThreadPool.QueueWorkItem(new WorkItemCallback(ipi));
            }

Ended up getting it to work with this:
public class ProductInformationTaskInfo
{
    public productinformation ProductInformation;

    public ProductInformationTaskInfo(productinformation pi)
    {
        ProductInformation = pi;
    }
}

public class PI
{
    foreach (var item in _list)
    {
        ProductInformationTaskInfo pi =
          new ProductInformationTaskInfo(item);
        smartThreadPool.QueueWorkItem
          (new WorkItemCallback
            (ImportProductInformation), pi);
    }

    public static object ImportProductInformation(Object _pi)
    {
        ProductInformationTaskInfo pi = (ProductInformationTaskInfo)_pi;
        var item = pi.ProductInformation;

        // Do work here
    }
}

A: I don't know or have the SmartThreadPool, the following is approximate:
foreach (var item in _list)
{
   var itemCopy = item;
   smartThreadPool.QueueWorkItem
              (dummy => ImportProductInformation(itemCopy));
}

You may have to do some fixing.
This works because the lambda captures a variable from the containing method. And that's why you need itemCopy.
But note that the normal ThreadPool is not suited for longrunning tasks, the same may hold for the SmartThreadPool. It should also keep a limit on the number of threads, and when ImportProductInformation does mainly I/O threading might not help at all.

A: You can use anonymous methods:
int a = 15;
String b = "hello world!";
ThreadPool.QueueUserWorkItem((state)=>SomeFunction(a,b));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disconnect backend Writer from BufferedWriter A java.io.BufferedWriter#close() also closes the Writer that was given to the constructor.
But I have (provided by third party; can't be changed) a special subclass that I only need to write part of the output with. More data need to be written to the underlying OutputStream further up the call stack. So while I can just #flush the writer instead of #closeing it, I can't guarantee it won't be closed by the garbage collector before the caller is finished with the OutputStream.
Can I stop the propagation of #close to the OutputStream? Preferably without writing all the potentially very large data into a temporary array.


text:
Q: Validate email python library runs really slow on AWS We would like to use the following python library to validate email addresses by smtp check: https://pypi.python.org/pypi/validate_email
The strange thing is that from locally it responds in 1 sec, but if we deploy it to an AWS ec2 instance, the response time jumps up to 5-6 sec. We already asked the support to remove the email sending limit and open the ports for us.
Does anyone have any idea why is it this slow?
Thanks.


text:
Q: Spatial Query: Polygon Attribute to be added to point data I am trying to get to grips with a spatial query. I have a table of polygons, that are Zones within my county. there are 38 of them. I then have premise data. I would like to run a query to show all the premises that fall within/intersect with these polygons.
My tables are as follows

*

*AB_BLPU (geometry address point data from Ordnance Survey)

*AB_Classification (Ordnance Surveys data)

*AB_Class_Schema (a lookup table for the classification table)

*Zones (this table is made up of 38 polygons, these are labelled by the Division they belong to e.g., East, North etc

I would like my results to be a list of premises with the Zone and Division they belong to but only giving me Residential premises i.e. "R".
I have tried this SQL code:
SELECT
    B.UPRN, B.X_COORDINATE, B.Y_COORDINATE, B.GEOMETRY, SA.Division, SA.Zone_Name
FROM  dbo.AB_BLPU AS B
LEFT OUTER JOIN dbo.AB_CLASSIFICATION AS C ON B.UPRN = C.UPRN
LEFT OUTER JOIN dbo.AB_CLASS_SCHEMA AS S ON C.CLASSIFICATION_CODE = S.Concatenated
LEFT OUTER JOIN GEO_DATA.Zones AS SA ON B.GEOMETRY.STIntersects(SA.GEOMETRY) = 1
WHERE (C.CLASS_SCHEME LIKE 'Address%') AND (S.Primary_Code LIKE 'R')

But I get the following error:

Msg 6522, Level 16, State 1, Line 2
A .NET Framework error occurred during execution of user-defined routine or aggregate "geometry":
System.ArgumentException: 24144: This operation cannot be completed because the instance is not valid. Use MakeValid to convert the instance to a valid instance. Note that MakeValid may cause the points of a geometry instance to shift slightly.
System.ArgumentException:

Yet when I run the same SQL code but with the Division polygon table (which only has three polygons in it, it works and I get 350,000 ish results. See below:
SELECT
    B.UPRN, A.DPADDRESS, B.X_COORDINATE, B.Y_COORDINATE, A.POST_TOWN, A.POSTCODE, B.GEOMETRY, O.ID
FROM dbo.AB_BLPU AS B
LEFT OUTER JOIN dbo.AB_CLASSIFICATION AS C ON B.UPRN = C.UPRN
INNER JOIN dbo.AB_DPADDRESS AS A ON B.UPRN = A.UPRN
LEFT OUTER JOIN dbo.AB_CLASS_SCHEMA AS S ON C.CLASSIFICATION_CODE = S.Concatenated
LEFT OUTER JOIN GEO_DATA.Division AS O ON B.GEOMETRY.STIntersects(O.GEOMETRY) = 1
WHERE (C.CLASS_SCHEME LIKE 'Address%') AND (S.Primary_Code LIKE 'R')
and O.ID is not null
order by b.UPRN asc

Can anyone suggest how to fix the issue? Why is it working for one polygon table but not one with 38 polygons?
Thanks


text:
Q: How to use Google Earth on iPhone? I am just wondering that is there any way to integrate the Earth browsers in an iPhone app (native or web).
Is there any way or any suggestion friend, this is an open discussion so please let ideas flow in.
Thank you All,

A: It is currently not possible. Read this.


text:
Q: Solving the congruence relation $90\equiv 6 \pmod n$ A family member of mine is currently taking high school Algebra 2 and is learning about the basics of modular arithmetic. The following question was asked of the students:

Find all integers n that satisfy the following:
$90\equiv 6 \pmod n$

The family member asked me for help, as she was stuck. But I too was stumped. It has been two years since I took Algebra 2, and I barely remember modular arithmetic. I seem to remember that $90\equiv 6 \pmod n$ means that 90 mod n = 6 mod n -- however, I am not sure how that can help me solve the problem.
I know this is a rather elementary question so I apologize if it has already been answered. That said, I have not been able to find an answer so far, as most sources deal with equations where the unknown value is something other than the one "inside" the mod parenthesis.

A: $90\equiv6\pmod n$  means $n$ divides $90-6,$ so the solutions for $n$ are the factors of $84.$


text:
Q: Which one to use: "I have constructed skills" or "I have built skills"? I want to express I improved and got new skills and now also I do as well since I started to work.
1) I have constructed skills.
2) I have built skills.
Which one is correct? Or is there other way to express this in common?

A: Generally an individual learns new skills,  then improves on their skills until they master those skills.

Learn is defined by dictionary.com as:

to acquire knowledge of or skill in by study, instruction, or experience

Improve is defined by dictionary.com as:

to bring into a more desirable or excellent condition:

Master is defined by dictionary.com as:

to make oneself master of; become an adept in:

You can use either one depending on how much experience you have with the skill set. Generally if you have (using your phrase as a given example):

*

*no experience in the skill, you will be learning that skill

*

*e.g. I have learned new skills.

*some experience in the skill, you will be improving that skill

*

*e.g. I have improved on my [new] skills.

*lots of experience in the skill, you will have mastered that skill

*

*e.g. I have mastered my skills.


text:
Q: get value of http request headers in php I am sending customer header in AJAX call,
$.ajaxSetup( {
     data: {csrf_token : csrf},
     headers: {"Csrf_token" : csrf}
    });

Below is content which i seen in Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:325
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:ci_session=kd817592v16s0p5b2f502hg39rs7olnu; csrf_cookie=22a1c908f3f036c90c2d0bf0f9b19497
Csrf_token:22a1c908f3f036c90c2d0bf0f9b19497
Host:testurl.com
Origin:http://testurl.com
Pragma:no-cache
Referer:http://testurl.com/xxx
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
X-Requested-With:XMLHttpRequest

But when i print this in PHP it only return below, i could not see my custom header "Csrf_token"
> Array ( [X-Forwarded-For] => 57.73.33.1 [Cookie] =>
> `ci_session=kd817592v16s0p5b2f502hg39rs7olnu;
> csrf_cookie=22a1c908f3f036c90c2d0bf0f9b19497 [Accept-Language] =>
> en-GB,en-US;q=0.8,en;q=0.6 [Accept-Encoding] => gzip, deflate
> [Referer] => http://testurl.com/xxx [X-Requested-With] =>
> XMLHttpRequest [Accept] => */* [Content-Type] =>
> application/x-www-form-urlencoded; charset=UTF-8 [User-Agent] =>
> Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like
> Gecko) Chrome/54.0.2840.99 Safari/537.36 [Origin] =>
> http://testurl.com[Cache-Control] => no-cache [Pragma] => no-cache
> [Content-Length] => 325 [Connection] => close [Host] => testurl.com )`

How can i get that customer header in PHP? I am using codeigniter,

A: I only got output by below,
$.ajaxSetup( {
     data: {csrf_token : csrf},
     headers: {"csrf-token" : csrf, "csrf_token1" : csrf}
    });

It will not print values with _ name but can print with - names.
Csrf-Token : "22a1c908f3f036werc90c2d0bf0f9b19497"

A: Use this
$headers = $this->input->request_headers();

link : https://www.codeigniter.com/user_guide/libraries/input.html#CI_Input::get_request_header


text:
Q: Proof that Namba Forcing preserves stationary subsets of $\omega_1$ I am looking for a proof (or reference) of the fact that Namba Forcing preserves stationary subsets of $\omega_1$. This fact is stated and used throughout the literature(whenever you google it you'll find examples), though no one is refering to a proof or giving one.
I will state a few relevant definitions regarding Namba forcing.
With Succ$_T(t)$ we denote the set of all immediate successors of $t$ in the tree, ie Succ$_T(t)=\{t^\frown \alpha \ | \ t^\frown \alpha\in T  \} $
With trunk$(T)$ we denote the initial segment of the tree where the nodes didn't start to branch off, ie $t$ = trunk$(T)$ iff $\forall s\in T : \ s\upharpoonright |t|=t$.
Namba Forcing has the following poset
$
 P = \{T\subset \omega_2^{<\omega_1} \ | \ T $ is a tree and $ \forall t\in T \ t $ has an extension $ s $ such that $ |Succ_T(s)|=\aleph_2    \}$
$P$ is ordered by inclusion: $T\leq S$ iff $T\subseteq S$, ie smaller trees are stronger.
So far, I have only found some unclear hints towards a proof I am looking for: In Proper Forcing - Shelah chapter XII, a class of forcings $UP_0$ is defined, and state that it preserves stationary subsets of $\omega_1$. See Claim 3.2 4) page 407. At the top of page 395 it states that Namba forcing belongs to this class. Though no proof is given and the book refers to a paper by Shelah, unclear which one.

A: See the appendix of the following paper:
Topological spaces after forcing
The ``A2 Theorem'' on page 86 is what you are looking for.


text:
Q: "System" using abnormal high CPU usage linked to NVIDIA graphic card I know many they have been many discussions about the "system using high CPU" already and I have been trying to solve this problem on my Dell XPS 15 9510 with an NVIDIA RTX 3050Ti ( relevant for later) using many solutions from users and I have concluded using Windows Performance Analyser that the process using all that power was "Nvlddmkm.sys", so I tried reinstalling the driver but it doesn't work.
Then I tried messing with the NVIDIA Control Panel and found out the weirdest thing:
When I'm at idle, no apps running, system is using 8-20% of CPU usage killing my battery life
But when I simply open the NVIDIA control panel and Select the "Adjust image setting with preview" page, system goes down on the task manager to about 0.1% of CPU usage and my battery life is back to normal ! It doesn't work on any other page of the NVIDIA Control Panel.
I'm running windows 11, with an Intel i7 11800H 2.30GHz , NVIDIA RTX3050Ti graphics card, 16gb of ram.
Do you have any idea why that is how i could fix this issue (without having to open the NVIDIA control panel all the time) ?
Here are the results of the WPA
With the symbols

A: This EXACT same issue occured on my Laptop 2 days ago, even with the CPU usage going down when being tabbed into the NVIDIA control panel, and the Nvlddmkm.sys being the main problem.
After a lot of simply trying things, just disabling the ingame overlay in the GeForce Experience settings solved it for me.
The CPU usage from "System" is now Back to >1%.


text:
Q: Using Lagrange's multiplier method, find the shortest distance between the line y=10-2x and the ellipse $\frac{x^2}{4}+\frac{y^2}{9}=1$
Using Lagrange's multiplier method, find the shortest distance between the line $y=10-2x$ and the ellipse $\frac{x^2}{4}+\frac{y^2}{9}=1$.

My work:
Let the point on ellipse be $(2\cos\theta, 3\sin\theta)$
Let $F=(x-2\cos\theta)^2+(y-3\sin\theta)^2+\alpha(2x+y-10)$.
I partially diffentiated $F$ wrt $x$,$y$ and $\theta$ equated to $0$.
I get $\tan\theta=\frac{3}{4}$ and $\alpha=-2$
The point on ellipse I get is $(\frac{8}{5},\frac{9}{5})$ and the point on line I get is $(\frac {18}{5}, \frac{14}{5})$
Is this method correct? Can I take $\theta$ to be an independent variable, and differentiate wrt to it?

A: Although your solution method is fine, I suspect that whoever gave you this exercise intended for you to use the equation of the ellipse directly instead of parameterizing the curve. Once you've done the latter, you have a single-variable problem for which there's not much point in using a Lagrange multiplier: you can compute the distance of the parameterized point to the line and minimize that directly.
The intended solution is likely something along these lines: The square of the distance from a point $(x,y)$ to the line is given by $$f:(x,y)\mapsto{(2x+y-10)^2\over5}.$$ You are to minimize this function subject to the constraint $g(x,y)=0$, where $g:(x,y)\mapsto\frac{x^2}4+\frac{y^2}9-1$, so form the function $F:(x,y,\lambda)\mapsto f(x,y)-\lambda g(x,y)$, set the partial derivatives of $F$ to zero and solve for $x$, $y$, $\lambda$. This will give you critical points of $f$ that you'll still have to test to see which are minima.

A: I think it should be
$$F=(x-t)^2+(y-s)^2+\alpha(2x+y-10)+\beta\left(\frac{t^2}{4}+\frac{s^2}{9}-1\right),$$
but I think it's better to solve your problem without Lagrange multipliers.

A: Alternatively: you can find the tangent line to the ellipse that is parallel to the line $y=10-2x$.
The tangent line to the ellipse at the point $(x_0,y_0)$ must have the slope $-2$:
$$\left(\frac{x^2}{4}+\frac{y^2}{9}\right)'_x=(1)'_x \Rightarrow \frac{x}{2}+\frac{2y}{9}y'=0 \Rightarrow y'=-\frac{9x}{4y} \Rightarrow$$
$$y'(x_0)=-\frac{9x_0}{\pm 4\cdot3\sqrt{1-\frac{x_0^2}{4}}}=-2 \Rightarrow x_0=\pm\frac{8}{5} \Rightarrow y_0=\pm\frac95.$$
Note: In general, there can be two tangent lines and $x_0=-\frac85,y_0=-\frac95$ must be ignored as it is the furthest point from the given line (i.e. the max distance).
Then you should find the distance from the point $(\frac85,\frac95)$ of ellipse to the line $y=10-2x$.

A: $\frac{x^2}{4} + \frac{y^2}{9}$ can be made into $ 1 = 9x^2 + 4y^2 = 36 $ which can be made into $9cos^2(\theta) + 4sin^2(\theta) = 36$. This should help simplify your calculations.


text:
Q: While compiling COM server with Matlab Builder NE, I keep on getting the error : "Description: MCR instance is not available" I am trying to compile a COM object in Matlab 2011a using Matlab Builder NE.
I managed to build and package it, deploy it, and even to start the COM server.
I am using the following command in Matlab

c = actxserver('MyFirstComServer.Class1');

However, when I try to run any method on this handle, I get an error message like that:

c.GetNames(0,'')
  ??? Invoke Error, Dispatch Exception:
  Source: MyFirstComServer.Class1.1_0
  Description: MCR instance is not available

I have found something on the web related to it, however, it did not help me
http://www.mathworks.com/support/solutions/en/data/1-2VS4TC/index.html?product=MN&solution=1-2VS4TC
Does anybody have any idea what to do?
Edit:
I've found out that the problem happens only if I call the component from Matlab.. This might have to do something with MCR confusion, the COM component uses the same MCR that Matlab uses.

A: I've found out that the problem happens only if I call the component from Matlab.. This might have to do something with MCR confusion, the COM component uses the same MCR that Matlab uses.
Edit(1) From Builder NE manual.

Testing with the MCR
  When you test with the MCR, keep in mind that the MCR is an instance of
  MATLAB. Given this, it is not possible to load the MCR into MATLAB.
  For example, if you build a generic COM component with the Deployment
  Tool from MATLAB Builder NE, you generate a DLL.
  If you then try to test the component with an application such as actxserver,
  which loads its process into MATLAB, you are effectively loading the MCR
  into MATLAB, producing an error such as this:
  mwsamp.mymagic(3,[],[])
  ??? Invoke Error, Dispatch Exception:
  Source: tmw1.Class1.1_0
  Description: MCR instance is not available
  Therefore, understand the behaviors of third-party processes before
  attempting to test them with the MCR.
  If you are uncertain about the behavior of these processes, contact your
  developer or systems administrator.


text:
Q: Creating powershell script to get show on desktop enabled + rename with hostname I'm just a junior programmer, just started with programming and because my work requests me to create some handy powershell scripts I was wondering if you can help me with a particular one.
We have a lot of customers with a lot of servers. When they are newly installed I do check them and after that we do regular maintenance. Because each customer has several servers with different roles I want to have the "Computer" icon on my desktop.
I can do that by clicking start -> rightclick Computer -> Enable "Show on Desktop"
Furtheron I want to have this Computer icon renamed to the hostname (because the hostname tells me it's role in the domain)
Now my goal is to create a powershell script that creates this computer icon with hostname for all the server in the domain.
I've tried to search my way to the usual search engines and came up with this:
1) Locate with regedit [HKEY_CLASSES_ROOT\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D} rename LocalizedString to LocalizedString.Old
2) Now switch to Regedit32 Create a new VALUE type Expand_SZ name it LocalizedString On XP and Windows 2000 with SP3 replace LocalizedString with %Username% at %Computername%
Which isn't suitable because we use W2K8R2SP1 servers.
After that I ended up with this script:
$ComputerName = "Localhost"
$Hive = "CurrentUser"
$Key = "Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel"
$MyComputer = "{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
$UserFiles = "{59031a47-3f72-44a7-89c5-5595fe6b30ee}"
$Kind = [Microsoft.Win32.RegistryValueKind]
$RegHive = [Microsoft.Win32.RegistryHive]$hive
$RegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($RegHive,$ComputerName)
$MyComputerValue = ($RegKey.OpenSubKey($Key)).GetValue($MyComputer)
$UserFilesValue = ($RegKey.OpenSubKey($Key)).GetValue($UserFiles)
if ($MyComputerValue -eq $null -or $MyComputerValue -eq 0)
{
    $Computer = $regKey.OpenSubKey($RootKey,$true)
    $Computer.SetValue($MyComputer, 1,$Kind::DWord)
}
if ($UserFilesValue -eq $null -or $UserFilesValue -eq 0)
{
    $User = $regKey.OpenSubKey($RootKey,$true)
    $User.SetValue($UserFiles, 1,$Kind::DWord)
}

This doesn't seem to be doing anything at all.
I know this registry key is used for the computer on desktop:
"{20D04FE0-3AEA-1069-A2D8-08002B30309D}"=dword:00000000

Continued search...
So I found this:
To show the 'My Computer' icon on the desk"text-decoration:underline;">
[HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel]
Name = {20D04FE0-3AEA-1069-A2D8-08002B30309D}
Type =REG_DWORD
Value = 0
To change the 'My Computer' icon to computer or user name:
[HKCR\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}]
Name = LocalizedString
Type = REG_EXPAND_SZ
Data value = %computername% or any combination you like – eg %username% %computername%

However the second part keeps giving me an error and even if i can get it to work, i want to run the script onces and all servers in domain should be having this update.
Thanks for helping out.
Best regards,
Nick

A: Changing HKCR\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\LocalizedString is still suitable on Server 2008 R2, but you need to take ownership of the key and grant administrators full access to it first.


text:
Q: calcul of sum from variable location cell I want to calculate SUM this is my code:
 Dim lastrow As Integer
 Dim lastcol As Integer, thiscol As Integer = CInt(j)
 xlWorkSheet = CType(xlWorkBook.Sheets(ComboBox1.Text),Excel.Worksheet)
 xlWorkSheet.Activate()
 xlApp.Visible = True
 With xlWorkSheet
    xlWorkSheet.Select()
    j = (xlApp.Cells.SpecialCells(2).Row + 1 & vbCrLf&xlApp.Cells.SpecialCells(2).Column)
    lastrow = .Cells(.Rows.Count, 1).End(Excel.XlDirection.xlUp).Row
    lastcol = .Cells(1, .Columns.Count).End(Excel.XlDirection.xlToLeft).Column
    For thiscol = j To lastcol
        .Cells(lastrow + 1, thiscol).Value = _
        xlApp.Sum(.Range(.Cells(1, thiscol), .Cells(lastrow, thiscol)))
    Next
 End With

I want to use the variable 'j' as integer not string.


text:
Q: What is meant by 4 GL? I came across the term 4GL(generation language) in reading about Oracle ADF Busniess components . I want to know what exactly is 4GL ?
This is the actual quote from the book Oracle Fusion Guide:

Oracle ADF Business Components is the business services layer of choice in Oracle Fusion
      application development. Compared to other persistence layers, ADF Business Components
      provides exceptional built-in business application functionality and maximally declarative
      experience that makes it a perfect match for those who seek an end-to-end fourth generation
      language (4GL) Java EE development architecture.

A: I have almost always referred to 4GL languages as languages in which even a technical analyst can program in such as CASE (Computer Assisted Software Engineering) tools. However, apparently there is more to it than that per Wikipedia.
The company I work for works with Oracle ADF quite a bit and we have our own CASE tool for mobile development and so we also refer to our own language as a 4GL one. Specifically we call it out as such because it includes an IDE that generates code on the back end based on very simple flow charts and scripts. It can manage all the basic interactions with databases, files systems, repository, assets, promotion, history and distribution of the scripts in an easily accessible way. Oracle ADF has a similar system.
Given that I would say a 4GL language is any language that abstracts the details of development into a higher level that allows for more productivity or allows for technical analyst to be able to work with it.

A: The best explanation is one that covers all the generations:

*

*1st-gen is the machine opcodes. These are the binary (hexadecimal if you please) codes the computer actually understands and works with at the hardware level.

*2nd-gen is assembly language. These are human-readable labels for the actual opcodes, making it easier for a human to write a program without having to remember or constantly reference the numeric opcodes and location addresses of registers and logic/arithmetic units, etc.

*3rd-gen are most of the languages programmers actually code in today that are intended to produce programs that run on the computer as applications: C/C++, Basic/VB, Pascal/Delphi, etc. These languages are compiled into assembly language files, then references between those files are linked together and the results digested into machine code, but third-generation languages provide constructs such as logic loops, variables, and object-oriented principles in a form that make them easy for humans to work with and understand. They abstract a lot of the low-level logical thinking, allowing programmers to think in slightly bigger steps (though a key part opf computer science education is teaching students to think in small enough steps that a computer can follow).

*4th-gen are languages invented to communicate with other programs. Markup languages (XML/HTML), query languages (SQL), scripting languages (JavaScript), even some of your higher-level communications protocols like HTTP and SOAP are considered fourth-generation languages. These are not, directly, compiled into machine instructions; they instead exist to be interpreted by another program which then performs the task it was asked to do by the program it received.

To be honest, there's not a very clear dividing line anymore between 3rd-gen and 4th-gen. Some clearly are one or the other, like C/C++ (3rd) and SQL (4th). But, for instance, is Java considered 3rd-gen, because it's intended to create programs that are "applications" in their own right? Or is it 4th-gen, because Java's not compiled into machine code but instead into an intermediate language of bytecodes, that are then interpreted by a virtual machine environment (most of which are in turn hosted by some other program like a web browser or web server) that actually does what the programmer's code tells it to? The same could be asked of .NET languages like C#/VB, and of most of the functional languages, which require runtimes that hide all the nitty-gritty imperative logic and side-effects, so the programmer can think in more mathematical, evaluatory terms.

A: 4GL is a bit of a nebulous term.
It is an attempt to describe a language were the programmer is able to solve a domain specific problem without having to worry about problems that are not specific to the domain (like storage/memory/communication). All these low level constructs are abstracted away by the language.
There are have been many attempts to achieve this over the years none have been "very" successful. This is usually because to be effective the problem domain that the language covers is very specific (and thus has a limited audience (that does not mean that they are not popular just that the audience is small)).
Of course because the term is not well defined there is also some abuse of the term. Sometimes it can be used to define frameworks where you just plug in modules of code and the infrastructure takes care of all the low level stuff while the plugin deals only with items at the domain level.


text:
Q: Capturing a sectioned image from a canvas with responsive layout I have a canvas with various div elements serving as boxes that represent areas of the canvas to capture. When the capture takes place, it isn't exactly as displayed on the screen. How can I track and responsively capture the div sections as they appear?
As an example, attempting to capture the large purple section:

Here is the code from the component:
<template>

      <canvas ref="the-canvas" class="canvas">
      </canvas>
      <video class="video" ref="video" autoplay />

</template>

A: There are a couple of complicating factors that make it a bit hard here.
The drawImage method takes its image data from the original source. Meaning, you are not drawing a part of the video that is presented to you. You are cutting out a piece from the original image/video capture. That means that you have to calculate the difference between the video dimensions presented to you and the dimensions of the original video.
Since the video 'overflows' out of the container on either the left and right or on the top and bottom side, you will have to account for that and add an offset to either the top or left.
Lastly, to get the image as presented on screen, you will have to stretch by providing the profile-box dimensions to drawImage.
To put it all together:
<template>

      <canvas ref="the-canvas" class="canvas">
      </canvas>
      <video class="video" ref="video" autoplay/>

</template>


text:
Q: How to et to data-thumb I have an img which looks like this:
<img data-thumb="//i4.ytimg.com/vi/G9S_E2NgSM8/mqdefault.jpg" src="http:///yts/img/pixel-vfl3z5WfW.gif" alt="Miniatuur" width="182">

I want to do something with the url resided in data-thumb. If it was img src I would have used prop or attr, I tried this for data-thumb but it doesn't work. How do get to the url in data-thumb with Jquery? (couldn't find anything on internet)

A: $('img').data('thumb');

See http://api.jquery.com/data/ for more.


text:
Q: Populate an excel object with List entry items I have a requirement that requires generation of an Excel document programmatically in SharePoint. I need to use an Excel template that has labels like
Name:
Designation:
Email:

I have a list with the same columns. I need to fetch data from this list and populate instances of the aforesaid template and save it.
Name : XYZ
Designation : ABC
Email : 1@a.com

This has to be done programmatically. Any idea how I do it?

A: So what did you write so far?
You could write a solution and let it run maybe on item-created or whatever kind of occurence you want it to happen. Then you need a Excel-Library (Aspose etc.) to create an Excel File. In the SPContext you are able to get List-Items and so you can write them to a Excel-File.


text:
Q: How to check if any module in a Python package imports from another package? I want to ensure all modules within one package ("pkg-foo") don't import from another package ("pkg-block").
Update: I know there are many black magic ways to import modules due to Python's dynamism.  However, I am only interested in checking explicit imports (e.g. import pkg.block or from pkg.block import ...).
I want to enforce this via a unit test in pkg-foo that ensures it never imports from pkg-block.
How can I accomplish this?  I use Python 3.8+ and am looking to use either built-ins or perhaps setuptools.
Current Half-Baked Solution
# pkg_resources is from setuptools
from pkg_resources import Distribution, working_set

# Confirm pgk-block is not in pkg-foo's install_requires
foo_pkg: Distribution = working_set.by_key[f"foo-pkg"]
for req in foo_pkg.requires():
    assert "pkg-block" not in str(req)

However, just because pkg-block is not declared in setup.py's install_requires doesn't mean it wasn't imported within the package.  So, this is only a half-baked solution.
My thoughts are I need to crawl all modules within pkg-foo and check each module doesn't import from pgk-block.

A: So my suggestion is to conceptually split this problem into two parts.
First sub-problem: determine all of the modules imported in pkg-foo. Let's use mod_foo to be some arbitrary imported module in pkg-foo
Second sub-problem: determine if any mod_foo are from pkg-block. If none of these modules are in pkg-block, pass the unit test, else, fail the unit test.
To solve the first sub-problem you can use the class modulefinder.ModuleFinder. As shown in the example from the documentation, you can do modulefinder.ModuleFinder.run_script(pathname) for each module in pkg-foo. Then you can get the module names by grabbing the keys from the dict modulefinder.ModuleFinder.modules. All of these modules will be your mod-foo modules.
To solve the second sub-problem, you can use mod_foo.__spec__ As mentioned here, mod_foo.__spec__ will be an instance of 'importlib.machinery.ModuleSpec' which is defined here. As described in the documentation just linked to, this object will have the attribute name which is:

A string for the fully-qualified name of the module.

Therefore we need to check to see if pkg-block is in the fully qualified name given by mod_foo.__spec__.name for each mod_foo.
Putting this all together, something along the lines of the following code should do what you need:
import modulefinder

def verify_no_banned_package(pkg_foo_modules, pkg_ban):
    """
    Package Checker
    :param pkg_foo_modules: list of the pathnames of the modules in pkg-foo
    :param pkg_ban: banned package
    :return: True if banned package not present in imports, False otherwise
    """

    imported_modules = set()

    for mod in pkg_foo_modules:
        mod_finder = modulefinder.ModuleFinder()
        mod_finder.run_script(mod)
        mod_foo_import_mods = mod_finder.modules.keys()
        imported_modules.update(mod_foo_import_mods)

    for mod_foo in imported_modules:
        mod_foo_parent_full_name = mod_foo.__spec__.name
        if pkg_ban in mod_foo_parent_full_name.split(sep="."):
            return False
    return True

A: I think the easiest way in your case is to mock a module that shouldn't be imported, i.e. pkg-block. In order to mock a module put it to the very beginning of sys.path, probably the easiest way to do so is to create a fake module (or temporary replace original one) in the project folder, so it would end up in your PYTHONPATH immediately. This will "redirect" all imports to your mock module. In the mock module itself put something like this:
print(f'Module {__name__} imported')

def __getattr__(name):
    print(f'Imported attribute {name} from module {__name__}')

The code above will print a line informing you that module or its attribute was imported, this would work for direct module imports and from imports, for imports inside functions, for imports with importlib (except importing by path, but I find this too esoteric). In order to simplify detection of imports in unit tests you probably want to raise an exception instead of just printing. You also don't have to have specific tests to verify that imports are not happening, instead just run your regular test suite for pkg-foo and see if any tests are failing due to import-specific exception.
Example:
Assume the following file structure:
|---main.py
|
\---pkg
    |---block.py
    |---foo.py
    |---__init__.py

where pkg/block.py
print(f'Module {__name__} imported')

def __getattr__(name):
    print(f'Imported attribute {name} from module {__name__}')

pkg/foo.py
import importlib

import pkg.block
from . import block
from .block import abc

importlib.import_module('pkg.block')

def from_function():
    from pkg.block import from_function

main.py
import pkg.foo

if __name__ == '__main__':
    pkg.foo.from_function()

then after executing main.py you'll get:
Module pkg.block imported
Imported attribute __path__ from module pkg.block
Imported attribute abc from module pkg.block
Imported attribute abc from module pkg.block
Imported attribute __path__ from module pkg.block
Imported attribute from_function from module pkg.block
Imported attribute from_function from module pkg.block


text:
Q: angular controller-directive data binding - bind property inside object I have two properties in my scope name and city.
If I change city, it reflects in directive. But when I change name, it is not reflecting in directive. I have intentionally passed name from obj object because I am trying to achieve data binding inside object.
Can some one please help how to bind property inside a object, so that the data binding still works.
I think this is where something must be wrong
 $scope.obj = { prop: $scope.name };

var myApp = angular.module('myApp',[]);

myApp.directive('passObject', function() {
    return {
        restrict: 'E',
        scope: { obj: '=', city: "=" },
        template: '
Hello, {{obj.prop}}! from {{city}}
'
    };
});

myApp.controller('MyCtrl', function ($scope) {
    $scope.name="manu";
  $scope.city = "hyderabad";
    $scope.obj = { prop: $scope.name };
});

    Name: <input ng-model="name"/>

    City: <input ng-model="city"/>

    <pass-object obj="obj" city="city"></pass-object>

A: I took your code and added a $scope.$watch to it to update the model $scope.obj on change of $scope.name, works fine now.
`
var myApp = angular.module('myApp',[]);

myApp.directive('passObject', function() {
    return {
        restrict: 'E',
        scope: { obj: '=', city: "=" },
        template: '
Hello, {{obj.prop}}! from {{city}}
'
    };
});

myApp.controller('MyCtrl', function ($scope) {
    $scope.name="manu";
    $scope.city = "hyderabad";
    $scope.obj = { prop: $scope.name };

    $scope.$watch(
      function(){
        return $scope.name;
      },
      function(newVal,oldVal){
        $scope.obj.prop = $scope.name;
      },
      true
    );
});

`

A: Your $scope.obj.prop is binding to a string on another object namely $scope
Your directive will not be notified of the change as the two way binding needs to be done on the property itself.
Example:
var myApp = angular.module('application',[]);

myApp.directive('passObject', function() {
    return {
        restrict: 'E',
        scope: { name: '=', city: "=" },
        template: '
Hello, {{name}}! from {{city}}
'
    };
});

myApp.controller('MyCtrl', function ($scope) {
    $scope.name="manu";
    $scope.city = "hyderabad";
});

    Name: <input ng-model="name"/>

    City: <input ng-model="city"/>

  <pass-object name="name" city="city"></pass-object>

If you really want to use your structure you can use $watch as Pramit Kundu showed in his answer, OR you can use a function to get the value.
Example 2
var myApp = angular.module('application',[]);

myApp.directive('passObject', function() {
    return {
        restrict: 'E',
        scope: { obj: '=', city: "=" },
        template: '
Hello, {{obj.prop()}}! from {{city}}
'
    };
});

myApp.controller('MyCtrl', function ($scope) {
    $scope.name="manu";
    $scope.city = "hyderabad";
    $scope.obj = { prop: function(){ return $scope.name; } };
});

    Name: <input ng-model="name"/>

       City: <input ng-model="city"/>

   <pass-object obj="obj" city="city"></pass-object>

I think we tend to use $scope.$watch when we are not supposed to seeing that we can overcome the issue by binding correctly to scope or to use a function


text:
Q: Problem storing laravel-medialibrary-pro media to AWS S3 I feel like I must be missing something very simple but I've lost track of everything I've tried over the past 3 days... I'm using medialibrary-pro for the temporary upload functionality on attachment to upload direct to S3.
First, my configs:
.env
MEDIA_DISK="s3-media"

config/filesystems.php has my s3 disk defined:
        's3-media' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
        'endpoint' => env('AWS_ENDPOINT'),
        'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        'root' => 'media-manager'
    ],

media-library.php is stock generated by artisan, the disk name you can see above is set in my .env file:
return [
'temporary_file_upload' => [
    'rules' => 'file|mimes:png,jpg,jpeg,gif|max:2048',
    'disk' => 's3-media',
    ],
];

My form blade view contains:
<x-media-library-attachment name="media" rules="mimes:png,jpg,jpeg,gif|max:2048"/>

My controller has:
$media
   ->addFromMediaLibraryRequest( $request->get('media') )
   ->toMediaCollection('user-media', 's3-media');

And now what happens...

*

*I drag an image over to the attachment container on the form view, it appears to complete successfully and I see the thumbnail of the image I just selected.

*

*The attachment uploads directly to S3 and I confirm it's there.

*The temporary_uploads table shows a model fo the upload.

*The media table shows a model for the upload with the model_type as TemporaryUpload and the collection_name as default.

*Now I click the submit on my form. and get the following exception:
fopen(/srv/users/username/apps/app-name/storage/media-library/temp/HSutOfGcDuysxkxNRJwMYo42L5RaclTU//file_name.jpg): Failed to open stream: No such file or directory

*

*The temporary_uploads table has the model deleted.

*The media table is updated showing model_type is MediaManager and collection_name is user-media, both as expected.

*BUT the files are now completely gone from S3. Nothing in storage/media-library or storage/media-library/temp either.

Any suggestions and help is greatly appreciated!

A: Seems like running save() on your model causes all sorts of problems. I went back to the example code at https://github.com/spatie/laravel-medialibrary-pro-app and rewrote my queries to use the create method rather than an insert. As soon as I took the $model->save() out of the equation everything worked as expected. I ended up creating a local media disk for the temp uploads and then when I process the upload I send it over to my s3-media disk.


text:
Q: LibreOffice cannot find file I wrote a really important document and saved it under documents folder. When I restarted my computer I discovered I cannot find the file in it's location. When I opened writer it tells me I need to restore the file, but when I click next it cannot find the file and says the restoration failed. What can I do?

A: In a teminal use these commands which may help you find your file:
'sudo updatedb'
'sudo locate '
Example:
'sudo locate .odt'
The above will list all files on your PC with the characters '.odt' in them.  .odt being the default file extension of LibreOffice Writer.
Perhaps the document is on a USB stick which has since been removed?


text:
Q: How do I access node on subnet from node on primary network? ]
I want to reach a node on the subnet, e.g. 192.168.2.239, from a node on the primary, e.g. 192.168.1.2.  Currently pinging from 192.168.1.2 to 192.168.2.239 gets no response. What do I need to set up in the definition of the bridge router?

A: You might not be able to have multiple subnets on the LAN side of these routers, they may only take two subnets, the WAN and one for the LAN.  (unless perhaps one put DDWRT or Tomato on one of them, and not for bridge mode, but for additional router or VLAN switch functionality).
So if you then don't have multiple subnets on the LAN then  two options are

*

*You could make them all 192.168.1.x/255.255.255.0. So change the 192.168.2.x addresses to 192.168.1.x.

*Or make the subnet 192.168.x.y/255.255.0.0. Then you can keep both the 192.168.1.x addresses and the 192.168.2.x addresses.
And by the way, those routers AFAIK even in router mode don't have an IP on each LAN port/interface. So I don't know why your Linksys which you've written in your diagram as being in bridge mode, can have an IP on each.
If it was in router mode it'd have an IP on the LAN side to access its web interface, but that's not associated with any particular LAN port. And if it was in bridge mode then it probably wouldn't have an IP for a web interface at all.
From my experience—and maybe Linksys is an exception to what I've seen—but when these NAT routers are in bridge mode they don't have any IP and have to be reset and go into router mode to access the web interface.


text:
Q: How to console log a single value from JSON object in Ionic 3 I am new Ionic and I am not able to access a single value from json object. I want to console log the value of timestamp which I get from API.
My TS code is something like this
viewTime(){

  let url = 'http://api.timezonedb.com/v2.1/get-time-zone?key=8304HG08VTGQ&format=json&by=zone&zone=Asia/Kolkata';

        this.http.request(url, this.config.options)
            .subscribe((response: any) => {
                   console.log(response);

                   this.data = response ;

                  console.log(this.data.timestamp); // i want this value to console log

                let date = new Date()
                 var myDate = new Date(new Date().getTime()+(7*24*60*60*1000));
                 console.log(myDate);

                 console.log("Current Date ",date);

                  this.nav.setRoot(AccountLogin);

                                }, (err) => {
                                let alert = this.alertCtrl.create({
                                title: 'Error',
                                subTitle: 'Please check your zone',
                                buttons: ['OK']
                                        });
                                 alert.present();
                                 });
                                 }

My API looks like this:
{
"status": "OK",
"message": "",
"countryCode": "IN",
"countryName": "India",
"zoneName": "Asia/Kolkata",
"abbreviation": "IST",
"gmtOffset": 19800,
"dst": "0",
"zoneStart": -764145000,
"zoneEnd": 0,
"nextAbbreviation": "",
"timestamp": 1538838621,
"formatted": "2018-10-06 15:10:21"
}

How to access timestamp value in console log?

A: so here is the answer(map to json was missing)
let url = 'http://api.timezonedb.com/v2.1/get-time-zone?key=8304HG08VTGQ&format=json&by=zone&zone=Asia/Kolkata';

        this.http.request(url, this.config.options)
.map(res => res.json())
            .subscribe((response: any) => {

}

console.log(response.timestamp);

or
console.log(response['timestamp']);

should print the timpstamp.


text:
Q: Structure of a function altered by if statement Python There is the function a could either be in the form of client.LinearKline.LinearKline_get() or in the form of client.Kline.Kline_get(). a and b, (first_run) however the a,(second_run) does not work. c just combines a and b and is simplifies it. My previous post: issue . How would I be able to make 'c' work with getattr.
choice= 1

if choice == 1:
    a = "LinearKline"
    b = "LinearKline_get"
    c = "LinearKline.LinearKline_get"
else:
    a = "Kline"
    b = "Kline_get"
    c = "Kline.Kline_get"

first_run =getattr(getattr(client, a), b)()
second_run= getattr(client, c)()

A: Don't do it that way.  It's just the wrong path, and it will be unmaintainable in the long run..
def getChoice(client):
    if choice == 1:
        return client.LinearKline.LinearKline_get
    else:
        return client.Kline.Kline_get

first_run = getChoice(client)()
second_run= getChoice(client)()


text:
Q: Pyomo glpk solver Termination condition : other I'm fairly new to pyomo. I wrote a program and tried to solve it with glpk but I ended in the following problem:
{'Problem': [{'Name': 'unknown', 'Lower bound': -inf, 'Upper bound': inf, 'Number of objectives': 1, 'Number of constraints': 15361, 'Number of variables': 15369, 'Number of nonzeros': 46978, 'Sense': 'minimize'}], 'Solver': [{'Status': 'ok', 'Termination condition': 'other', 'Statistics': {'Branch and bound': {'Number of bounded subproblems': 0, 'Number of created subproblems': 0}}, 'Error rc': 0, 'Time': 0.2313551902770996}]}

The problem I guess is on the termination condition and all decision variables using model.pprint() seem to have the values of None.
Any idea how i could make the script to run properly and a find a solution.


text:
Q: libGDX and Eclipse - Could not find tools.jar I've been trying to generate an Eclipse project using libGDX, in order to use it with this tutorial. However, everytime I generate the project I get the error message:
Execution failed for task ':core:compileJava'.
Could not find tools.jar

The images below show the settings I use and the messages I get.

I'm using the most recent version of Eclipse and the Android SDK. I got the Android version of Eclipse through the installation program from the Eclipse website and I got the Android SDK through Eclipse. Everything is installed in the default folders. I've got the most recent versions of both the 32 and 64 bits versions of Java.
Could anyone tell me what I'm doing wrong?
PS. My question might be similar to this question: What exactly is "tools.jar" in the Android SDK?. However, the answer to that question only applies to Android studio users.

A: Check your installed JDK.
You have to set the system property "java.home" and the environment variable JAVA_HOME to a valid JDK.
Check gradle.properties file at the root of your project with the following property:
org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_74

org.gradle.java.home needs to point to a valid JDK location.
Without this file, you get the same error (Could not find tools.jar). With the file present, this is no longer an issue.

A: Just add this line to gradle.properties:
org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_131


text:
Q: Django setting a transaction for class-based redirect view I have the following class-based view with simple likes-toggling mechanics:
class PostLikeToggle(RedirectView):
def get_redirect_url(self, *args, **kwargs):
    post_id = kwargs.get('pk')
    post = get_object_or_404(Post, id=post_id)
    user = self.request.user
    if post.likes.filter(id=user.id).exists():
        post.likes.remove(user)
    else:
        post.likes.add(user)
    url_redirect = post.get_absolute_url(post_id)
    return url_redirect

I think of making this method as an atomic transaction, but not sure about the proper way to do that.
Am I on the right track?
class PostLikeToggle(RedirectView):
    @transaction.atomic
    def get_redirect_url(self, *args, **kwargs):

A: There are two ways of doing it, first is what you said:
class PostLikeToggle(RedirectView):
    @transaction.atomic
    def get_redirect_url(self, *args, **kwargs):

Second option:
def get_redirect_url(self, *args, **kwargs)
    try:
        with transaction.atomic():
            pass  # CRUD operations
    except IntegrityError:
        handle_exception()  # this will run after rollback


text:
Q: Cannot Import NPM Workspace Scoped Module Subfolder I currently working on this repository which uses NPM Workspace, and Turborepo. The repository consisted of many modules, just how a monorepo is. The general layout of the repository are as follows,
+-- src
    +-- package.json (workspace definition to all module under folder common and modules)
    +-- common
        +-- commonModule (@example/common-module)
            +-- package.json
            +-- tsconfig.json
            +-- src
                +-- index.ts (exports liba)
                +-- liba
                    +-- a.ts (exports code)
                    +-- index.ts (exports a.ts)
    +-- modules
        +-- mainModules (@example/main-module)
            +-- package.json
            +-- tsconfig.json
            +-- src
                +-- index.ts

The case is that in the src/modules/mainModules/src/index.ts I try to import the a.ts from @example/common-module. The first thing I tried are something like this,
import { a } from "@example/common-module/src/liba";

But the result after building it using tsc and running it using node 16 as usual. It gives out error that the module are not found, the error code are like this,
...
Error: Cannot find module '@example/common-module/src/liba'
...

While when I tried to import it from the root like,
import { lib } from "@example/common-module";

lib.a

It works just fine, node is able to find the modules corresponding to the import statement. Is node are not able to import through subfolder of a scoped modules? Or there are ways to get around this? All the modules do show up when I do npm list as well.
For reference all of the modules are using this exact tsconfig.json,
{
  "extends": "@tsconfig/node16-strictest/tsconfig.json",
  "compilerOptions": {
    "lib": ["ESNext"],
    "outDir": "dist"
  }
}

The extended file are just tsconfig base strictest version for node 16 that can be seen in their repository.


text:
Q: Lookup headers and selectively sum cells below it I am trying to find a specific column based on month (B1) and sum the cells under it. Furthermore, im trying to only sum the cells in that column by the designated region (D1). This is what I figured it would be but excel doesn't see it as a valid function.
=SUMIFS(ADDRESS(MATCH(A3,A:A,0)+10,MATCH(B1,3:3,0)):ADDRESS(MATCH(A3,A:A,0)+1,MATCH(B1,3:3,0)),A4:A$12,D1)

A: =SUMIFS(INDEX($1:$1048576,0,MATCH(B1,3:3,0)),A:A,D1)

The INDEX($1:$1048576,0,MATCH(B1,3:3,0)) returns the whole column where Row 3 equals B1.  Then sums that column where column A equals D1.
If you want to limit it to only Rows 4:12 like your current formula:
=SUMIFS(INDEX($4:$12,0,MATCH(B1,3:3,0)),$A$4:$A$12,D1)

A: The following will sum based on Month, Region, and Manager...
=SUMIFS(INDEX($D$4:$J$12,0,MATCH(B1,$D$3:$J$3,0)),$A$4:$A$12,D1,$B$4:$B$12,F1)

Hope this helps!


text:
Q: Numerically stable softmax Is there a numerically stable way to compute softmax function below?
I am getting values that becomes Nans in Neural network code.
np.exp(x)/np.sum(np.exp(y))

A: Extending @kmario23's answer to support 1 or 2 dimensional numpy arrays or lists. 2D tensors (assuming the first dimension is the batch dimension) are common if you're passing a batch of results through softmax:
import numpy as np

def stable_softmax(x):
    z = x - np.max(x, axis=-1, keepdims=True)
    numerator = np.exp(z)
    denominator = np.sum(numerator, axis=-1, keepdims=True)
    softmax = numerator / denominator
    return softmax

test1 = np.array([12345, 67890, 99999999])  # 1D numpy
test2 = np.array([[12345, 67890, 99999999], # 2D numpy
                  [123, 678, 88888888]])    #
test3 = [12345, 67890, 999999999]           # 1D list
test4 = [[12345, 67890, 999999999]]         # 2D list

print(stable_softmax(test1))
print(stable_softmax(test2))
print(stable_softmax(test3))
print(stable_softmax(test4))

 [0. 0. 1.]

[[0. 0. 1.]
 [0. 0. 1.]]

 [0. 0. 1.]

[[0. 0. 1.]]

A: The softmax exp(x)/sum(exp(x)) is actually numerically well-behaved. It has only positive terms, so we needn't worry about loss of significance, and the denominator is at least as large as the numerator, so the result is guaranteed to fall between 0 and 1.
The only accident that might happen is over- or under-flow in the exponentials. Overflow of a single or underflow of all elements of x will render the output more or less useless.
But it is easy to guard against that by using the identity softmax(x) = softmax(x + c) which holds for any scalar c: Subtracting max(x) from x leaves a vector that has only non-positive entries, ruling out overflow and at least one element that is zero ruling out a vanishing denominator (underflow in some but not all entries is harmless).
Footnote: theoretically, catastrophic accidents in the sum are possible, but you'd need a ridiculous number of terms. For example, even using 16 bit floats which can only resolve 3 decimals---compared to 15 decimals of a "normal" 64 bit float---we'd need between 2^1431 (~6 x 10^431) and 2^1432 to get a sum that is off by a factor of two.

A: Softmax function is prone to two issues: overflow and underflow
Overflow: It occurs when very large numbers are approximated as infinity
Underflow: It occurs when very small numbers (near zero in the number line) are approximated (i.e. rounded to) as zero
To combat these issues when doing softmax computation, a common trick is to shift the input vector by subtracting the maximum element in it from all elements. For the input vector x, define z such that:
z = x-max(x)

And then take the softmax of the new (stable) vector z

Example:
def stable_softmax(x):
    z = x - max(x)
    numerator = np.exp(z)
    denominator = np.sum(numerator)
    softmax = numerator/denominator

    return softmax

# input vector
In [267]: vec = np.array([1, 2, 3, 4, 5])
In [268]: stable_softmax(vec)
Out[268]: array([ 0.01165623,  0.03168492,  0.08612854,  0.23412166,  0.63640865])

# input vector with really large number, prone to overflow issue
In [269]: vec = np.array([12345, 67890, 99999999])
In [270]: stable_softmax(vec)
Out[270]: array([ 0.,  0.,  1.])

In the above case, we safely avoided the overflow problem by using stable_softmax()

For more details, see chapter Numerical Computation in  deep learning book.

A: There is nothing wrong with calculating the softmax function as it is in your case. The problem seems to come from exploding gradient or this sort of issues with your training methods. Focus on those matters with either "clipping values" or "choosing the right initial distribution of weights".


text:
Q: Displaying a specific image on a webpage using the output of paired select boxes There are lots of tutorials for making paired select boxes, which I've followed but I feel like I've hit the wall of my knowledge and available tutorials when it comes to populating an image div with the value selected in the second select box.
I'm trying to select an astronomical object, and then a colour filter (Red/Green/Blue) to "image it." By which I mean the wavelength of light the fictional telescope would photograph it in for a simulation programme for young telescope users.
I have photos of each object in each wavelength, I just need to be able to display Nebula M43 in the red wavelength. The script below is abridged but contains 3 options and the JavaScript I've put together to get it as far as populating the the second select box.
Can anyone help me with where I go from here? Even if its telling me the terminology I need to know to search for it myself would help.
Apologies for the poorly worded question - this is my first post on here and I'm still learning.

// object literal holding data for option elements
var Select_List_Data = {
  choices: {
    // name of associated select box

    // names match option values in controlling select box

    0: {
      text: ["Select Filter..."],
      value: ["Berkeley73Red (Rp)", "Berkeley73Green (V)", "Berkeley73Blue (B)"]
    },
    Berkeley73: {
      text: ["Red (Rp)", "Green (V)", "Blue (B)"],
      value: ["Berkeley73Red (Rp)", "Berkeley73Green (V)", "Berkeley73Blue (B)"]
    },
    Czernik27: {
      text: ["Red (Rp)", "Green (V)", "Blue (B)"],
      value: ["Czernik27Red (Rp)", "Czernik27Green (V)", "Czernik27Blue (B)"]
    },
    IC349: {
      text: ["Red (Rp)", "Green (V)", "Blue (B)"],
      value: ["IC349Red (Rp)", "IC349Green (V)", "IC349Blue (B)"]
    }
  }
};

// removes all option elements in select box
// removeGrp (optional) boolean to remove optgroups
function removeAllOptions(sel, removeGrp) {
  var len, groups, par;
  if (removeGrp) {
    groups = sel.getElementsByTagName("optgroup");
    len = groups.length;
    for (var i = len; i; i--) {
      sel.removeChild(groups[i - 1]);
    }
  }

  len = sel.options.length;
  for (var i = len; i; i--) {
    par = sel.options[i - 1].parentNode;
    par.removeChild(sel.options[i - 1]);
  }
}

function appendDataToSelect(sel, obj) {
  var f = document.createDocumentFragment();
  var labels = [],
    group, opts;

  function addOptions(obj) {
    var f = document.createDocumentFragment();
    var o;

    for (var i = 0, len = obj.text.length; i < len; i++) {
      o = document.createElement("option");
      o.appendChild(document.createTextNode(obj.text[i]));

      if (obj.value) {
        o.value = obj.value[i];
      }

      f.appendChild(o);
    }
    return f;
  }

  if (obj.text) {
    opts = addOptions(obj);
    f.appendChild(opts);
  } else {
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        labels.push(prop);
      }
    }

    for (var i = 0, len = labels.length; i < len; i++) {
      group = document.createElement("optgroup");
      group.label = labels[i];
      f.appendChild(group);
      opts = addOptions(obj[labels[i]]);
      group.appendChild(opts);
    }
  }
  sel.appendChild(f);
}

// anonymous function assigned to onchange event of controlling select box
document.forms["demoForm"].elements["category"].onchange = function(e) {
  // name of associated select box
  var relName = "choices";

  // reference to associated select box
  var relList = this.form.elements[relName];

  // get data from object literal based on selection in controlling select box (this.value)
  var obj = Select_List_Data[relName][this.value];

  // remove current option elements
  removeAllOptions(relList, true);

  // call function to add optgroup/option elements
  // pass reference to associated select box and data for new options
  appendDataToSelect(relList, obj);
};

// populate associated select box as page loads
(function() {
  // immediate function to avoid globals

  var form = document.forms["demoForm"];

  // reference to controlling select box
  var sel = form.elements["category"];
  sel.selectedIndex = 0;

  // name of associated select box
  var relName = "choices";
  // reference to associated select box
  var rel = form.elements[relName];

  // get data for associated select box passing its name
  // and value of selected in controlling select box
  var data = Select_List_Data[relName][sel.value];

  // add options to associated select box
  appendDataToSelect(rel, data);
})();
<form action="#" method="post" id="demoForm" class="demoForm">

  Target Name

    <select name="category">

      <option value="0" selected="selected">Select a target...</option>
      <option value="Berkeley73">Berkeley 73 (Cluster of Stars -40 sec. avg.)</option>
      <option value="Czernic27">Czernic27 (Open (galactic) Cluster -40 sec. avg.)</option>
      <option value="IC349">IC349 (Reflection Nebula -120 sec. avg.)</option>
    </select>

Filter

  <select name="choices" id="choices">

  </select>

  </fieldset>
</form>

A: Ok, so really what you need to do is call a function onchange when your user makes a choice from the options. Bear in mind that the options that you have paired may be changed by the user, so onchange, retrieve the image, then retrieve the desired colour, and then apply the filter. From "filter", it sounds like you want to put the colour over the image? In this case you could create a div and display it in absolute position (same position as the image div) and adjust the z index so that it displays over the image. I wrote some very quick pseudocode (no code - sorry :( ) in a function at the end of your javascript (which seems very long-winded? I didn't study it thoroughly - time issues) .
I created a div and put a placeholder image in it (you would populate your image into this div and put the filter over it)
EDIT: I updated the snippet with new code (erm.. it's quite different from yours) I have a placeholder image, but there is a commented out line that you can use to populate the image. It helps to set your baseurl in a variable like so:
    var baseurl = "https://www.yourdomain.com/images/";
    var $showimg = baseurl + $chosen + ".jpg"; /*or png etc*/

    $(".astro").attr("src",$showimg);

I commented the last line out just so that you could see the effect in the snippet.
Hope this helps (someone!)

$(document).ready(function() {

  $(function getimage() {
    $("#choice").change(function() {
      var $chosen = $("#choice option:selected").val();
      //alert($chosen);
      if ($chosen == "base") {
        alert("Please select an image")
      } else {
        /*set your image source*/
        var baseurl = "https://www.yourdomain.com/images/";
        var $showimg = baseurl + $chosen + ".jpg"; /*or png etc*/
        //alert ("img is " +$showimg);
        //$(".astro").attr("src",$showimg); use this, the next line is demo purposes
        $(".astro").attr("src", "https://images-eu.ssl-images-amazon.com/images/G/02/Gateway/Brightbuy/bb_green_1._CB457277258_SY260_.jpg");
      }
    });
  });

  $(function applyfilter() {
    $("#filter").change(function() {
      var $filter = $("#filter option:selected").val();
      $("#filtercol").get(0).style.setProperty("background-color", $filter);
      //alert("colour is " + $filter);
    });
  });

});
body {
  height: 100vh;
}

h4 {
  margin: 5px 0px;
  padding: 0px;
}

#category,
#filtercol {
  position: absolute;
  display: block;
  margin-top: 20px;
  margin-left: 50px;
  top: 40vh;
  width: 250px;
  height: 250px;
  border: 1px dashed grey;
}

.astro {
  opacity: 1;
  z-index: 10;
}

#filtercol {
  opacity: 0.1;
  z-index: 1;
}

  Target

<select id="choice">
  <option selected value="base">Please Select</option>
  <option value="Berkeley73">Berkeley 73 (Cluster of Stars -40 sec. avg.)</option>
  <option value="Czernic27">Czernic27 (Open (galactic) Cluster -40 sec. avg.)</option>
  <option value="IC349">IC349 (Reflection Nebula -120 sec. avg.)</option>
</select>

Filter

<select id="filter">
  <option>Red</option>
  <option>Green</option>
   <option>Blue</option>
</select>


text:
Q: Algebraic integers and characteristic polynomial Let $K/\mathbb{Q}$ be a number field of degree $n$. For $\beta \in K$ define the linear map (viewing $K$ as a $\mathbb{Q}$-vector space) $\theta_{\beta} : K \to K$ via $\theta_{\beta}(\gamma) = \beta\gamma$. Prove that $\beta$ is an algebraic integer if and only if the characteristic polynomial $\det(xI_n - \theta_{\beta})$ has integer coefficients.
So with $f(x) = \det(xI_n - \theta_{\beta})$ I was able to show that $f(\beta) = 0$ using the Cayley-Hamilton Theorem. So if $f$ has integer coefficients, then by definition, $\beta$ must be algebraic. However what about the converse? How to use the minimal polynomial (for which is easy to be shown that it has integer coefficients) to show that $f$ also does have integer coefficients?

A: Let $f(X) = \det(XI-\beta)$ as in the OP. (But $X$ is a transcendent variable.)
I will write $!K$ for the vector space over $\Bbb Q$ obtained from $K$ by applying the forgetful functor $!$, so $T:=(\beta I-\theta_\beta):!K\to !K$ is the zero morphism, so $\det T=0$. (We do not need Cayley-Hamilton. And moreover...)
This shows that assuming $f\in\Bbb Z[X]$, because also $f(\beta)=0$, the minimal polynomial of $\beta$ is a divisor of $f$, so it is in $\Bbb Z[X]$, gaussian Lemma, so $\beta$ is algebraic.

The converse, and the question.
Let us assume now that $\beta $ is algebraic.
Let $L$ be the subfield of $K$ generated by $\beta$ over $\Bbb Q$. Then $1,\beta,\dots,\beta^{k-1}$ is a basis of $!L$ over $\Bbb Q$, $k$ being the degree of $\beta$ over $\Bbb Q$.
Fix now some $x\in \Bbb Q$, and let us write the matrix of $$T(x):=(xI-\theta_\beta)\ ,\qquad x\in\Bbb Q\ ,$$ seen first as a morphism $!L\to\!L$, (later as $!K\to!K$,) w.r.t. this basis.
This matrix is $xI$ minus a companion matrix, and the companion matrix has only integer entries, since $\beta$ is algebraic.
Now consider a basis of $K:L$, and for each $\gamma$ in this basis the system $\gamma,\gamma\beta,\dots\gamma\beta^{k-1}$. The matrix of $T(x)$, restricted to the subspace generated by this system is again the same matrix, $xI$ minus integral companion matrix.
Pasting these system together, we get a basis of $K:\Bbb Q$, and the matrix of $T(x)$ is a diagonal repetition of the same block. Now $f(x) = \det T(x)$ holds for every $x\in\Bbb Q$, thus $f(X) = \det T(X)\in\Bbb Z[X]$.


text:
Q: Jquery clear select in the second populate I have this jquery and it is working fine. but the problem that i am facing when i select second time it will add the data to the previous results. and will not clear it.
I tried to use empty function and .html('') but it did not work.
$(document).ready(function(){  $("#cat").change(function(){
$.ajax(
{url:"maintenance_task.php",
data:   { cat_id : $("#cat option:selected").val() },
dataType: 'json',
success:function(json){
     $.each(json, function(i, value) {

        $('#task_type').append($('<option>').text(value).attr('value', i));
    });
  }});  });});

can anybody help me with this.
thanks in advance.

A: try this
$(document).ready(function(){
 $("#cat").change(function(){
   $.ajax({
      url:"maintenance_task.php",
      data:   { cat_id : $("#cat option:selected").val() },
      dataType: 'json',
      success:function(json){
        $('#task_type').html(' ');
        $.each(json, function(i, value) {
          $('#task_type').append($('<option>').text(value).attr('value', i));
        });
     }
  });
 });
});


text:
Q: QGIS 2.18 can't read multiple rasters in on geopackage I'm trying to add multiple rasters in one geopackage
But QGis 2.18 seems to be unable to deal with...
To add the rasters I use GDAL commands :
gdal_translate -projwin 578000 6270000 580000 6268000 -a_srs EPSG:2154 -of GPKG -co RASTER_TABLE=image1 -co TILE_FORMAT=JPEG d:\donnees\ortho.ecw c:\temp\test.gpkg
gdal_translate -projwin 579000 6275000 581000 6273000 -a_srs EPSG:2154 -of GPKG -co RASTER_TABLE=image2 -co APPEND_SUBDATASET=YES -co TILE_FORMAT=JPEG d:\donnees\ortho.ecw c:\temp\test.gpkg

Everything seems ok
But when I try to open the raster from QGis, I get this dialog but then nothing happens...

If I add only each image in one geopackage, it is ok but I would like to put 2 images in one geopackage.


text:
Q: How can we prevent Google Cloud API from swallowing exceptions? I sometimes get the following exception on put(). (Though in general, my code works fine.)
My  best guess is that Datastore internally encounters an indexing error (which there are no tools for diagnosing), but I am not sure because the error is swallowed with a Protobuf parsing problem.
In another case, a similar swallowing of exceptions, with Protobuf parsing message, was caused by a bug internal to Dataflow's own Datastore API, and the Dataflow team fixed that -- but here I am not using Dataflow at all.
How can I learn what is causing this?
Using Google Cloud API 0.28.
   ... at com.google.cloud.datastore.DatastoreImpl.put(DatastoreImpl.java:340)
    at com.google.cloud.datastore.DatastoreImpl.commitMutation(DatastoreImpl.java:380)
    at com.google.cloud.datastore.DatastoreImpl.commit(DatastoreImpl.java:386)
    at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:244)
    at com.google.cloud.RetryHelper.doRetry(RetryHelper.java:179)
    at com.google.cloud.datastore.DatastoreImpl$4.call(DatastoreImpl.java:387)
    at com.google.cloud.datastore.DatastoreImpl$4.call(DatastoreImpl.java:390)
    at com.google.cloud.datastore.spi.DefaultDatastoreRpc.commit(DefaultDatastoreRpc.java:131)
    at com.google.datastore.v1.client.Datastore.commit(Datastore.java:84)
    at com.google.datastore.v1.client.RemoteRpc.call(RemoteRpc.java:89)
    at com.google.datastore.v1.client.RemoteRpc.makeException(RemoteRpc.java:148)
    at com.google.rpc.Status.parseFrom(Status.java:323)
    java.lang.NoSuchMethodError: com.google.protobuf.GeneratedMessage.parseWithIOException(Lcom/google/protobuf/Parser;Ljava/io/InputStream;)Lcom/google/protobuf/Message;

A: I think this is a symptom of an older version of the com.google.protobuf:protobuf-java artifact making it onto your classpath. The GeneratedMessage.parseWithIOException method was added in com.google.protobuf:protobuf-java:jar:3.0.0.
One approach for preventing that is adding a dependencyManagement section to your pom file:
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java</artifactId>
      <version>3.0.0</version>
    </dependency>
  </dependencies>
</dependencyManagement>

Once the dependency issue is cleaned up, the client should be able to correctly parse Status protos and display the underlying error.


text:
Q: Create TBase objects from Thrift-generated classes in Scala I have some Scala classes I generated with Thrift (Scrooge). Now I need to somehow instantiate those as TBase class, b/c the TSerializer class needs this as an input
This is my approach:
  def createTestBinary(): String = {
    val proto = new TBinaryProtocol.Factory
    val err = new ClientError{}
    val binary = new TSerializer().serialize(err)
    ""
  }

ClientError is the generated class. How can I instantiate it or wrap it as a TBase member?
Any ideas how to do this? Thanks in advance!

A: You don't need TSerializer, that's for "vanilla" thrift, not for scrooge-generated classes.
You need to do something like this instead:
val transport = TMemoryBuffer(1024) // or whatever
err.write(new TBinaryProtocol(transport))
val binary = transport.getArray

A: for scrooge-generated classes you can use  JsonThriftSerializer:
import com.twitter.scrooge.JsonThriftSerializer
val serializer = JsonThriftSerializer(<scrooge-generated-classes>._codec)
Json.toJson(serializer.toString(<scrooge-generated-classes>))


text:
Q: sed: Can my pattern contain an "is not" character? How do I say "is not X"? How do I say "is not" a certain character in sed?

A: [^x]

This is a character class that accepts any character except x.

A: For those not satisfied with the selected answer as per johnny's comment.
'su[^x]' will match 'sum' and 'sun' but not 'su'.
You can tell sed to not match lines with x using the syntax below:
sed '/x/! s/su//' file

See kkeller's answer for another example.

A: There are two possible interpretations of your question. Like others have already pointed out, [^x] matches a single character which is not x. But an empty string also isn't x, so perhaps you are looking for [^x]\|^$.
Neither of these answers extend to multi-character sequences, which is usually what people are looking for. You could painstakingly build something like
[^s]\|s\($\|[^t]\|t\($\|[^r]\)\)\)

to compose a regular expression which doesn't match str, but a much more straightforward solution in sed is to delete any line which does match str, then keep the rest;
sed '/str/d' file

Perl 5 introduced a much richer regex engine, which is hence standard in Java, PHP, Python, etc. Because Perl helpfully supports a subset of sed syntax, you could probably convert a simple sed script to Perl to get to use a useful feature from this extended regex dialect, such as negative assertions:
perl -pe 's/(?:(?!str).)+/not/' file

will replace a string which is not str with not. The (?:...) is a non-capturing group (unlike in many sed dialects, an unescaped parenthesis is a metacharacter in Perl) and (?!str) is a negative assertion; the text immediately after this position in the string mustn't be str in order for the regex to match. The + repeats this pattern until it fails to match. Notice how the assertion needs to be true at every position in the match, so we match one character at a time with . (newbies often get this wrong, and erroneously only assert at e.g. the beginning of a longer pattern, which could however match str somewhere within, leading to a "leak").

A: From my own experience, and the below post supports this, sed doesn't support normal regex negation using "^".  I don't think sed has a direct negation method...but if you check the below post, you'll see some workarounds.
Sed regex and substring negation

A: In addition to all the provided answers , you can negate a character class in sed , using the notation [^:[C_CLASS]:] , for example , [^[:blank:]] will match anything which is not considered a space character .


text:
Q: How did they debug segmentation faults before protected memory? Now, when I make a programming mistake with pointers in C, I get a nice segmentation fault, my program crashes and the debugger can even tell me where it went wrong.
How did they do that in the time when memory protection wasn't available? I can see a DOS programmer fiddling away and crashing the entire OS when he made a mistake. Virtualization wasn't available, so all he could do was restart and retry. Did it really go like that?

A: well ..
a segfault is a really nice indicator that something is wrong but you still have to find the root cause. So if you ask the question how do you find the root cause than the answer is not much different today than it was then. Of course the languages and tools became easier to work with but the general taktik is the same:

*

*logging helps to find the area where your problem is. Binary search printf is a form of it.

*debugging, step by step, break points and watches

*refactoring to get a better understanding

*staring hard at the code

*look at the memory / core dump

*feeding it with different data

*showing it to other people

*switch to a language without pointers (and a new set of problems)
...

On a more abstract level you have three approaches:
1. work with the code
2. look at the program while it runs
3. look the results after it did something stupid
btw a pointer error does not have to create a segfault.
As a Amiga programmer I used pretty much all of it.
And yes restarts where common practise.

A: On the IBM 360, running Fortran batch jobs, we used to get hex core dumps. Such a dump could be as much as an inch thick of fan-fold green-and-white printer paper. It would tell what the registers were, and from there we could backtrack and figure out what the program was doing. We could find each subroutine and figure out where it stored its return address, so we could see the context. It would help to have an assembler listing of the program.

A:
I can see a DOS programmer fiddling away and crashing the entire OS when he made a mistake.

Yeah, that's pretty much what happened.  On most systems that had memory maps, location 0 was marked invalid, so that null pointers could be easily detected, because that was the most common case.  But there were lots of other cases, and they caused havoc.
At the risk of sounding like a geezer, I should point out that the current focus on debugging is not the way of the past.  Much more effort was previously made to write correct programs, rather than to remove bugs from incorrect programs.  Some of that was because that was our goal, but a lot was because the tools made things hard.  Try writing your programs on paper or on punched cards, not in an IDE, and without the benefit of an interactive debugger.  It gives you a taste for correctness.

A: Back in my day, we didn't have memory protection and all that snazzy business!  We used printf to determine where we were in the program, and we liked it!
Though in all seriousness, it usually meant we were just more careful.  Where malloc is called, there had to be a free somewhere else in the program, and such checking was rigorous because in the case of a problem, as you've clearly pointed out, segmentation faults are not helpful errors.
In the case of such errors, the best you could do is try to understand when such segmentation faults occur (using printf) and, looking at the code, determine why access to memory at that point was not valid and work backwards from there.
In essence, the same thing happens today, except we use debuggers to determine when errors occur, but you still have to understand why it happened, and it isn't always as simple as finding the line in which the error occurred.  Errors cause errors like a chain reaction, and if you were a C programmer in those days, you spent 20% of your time coding and the rest of the time pulling your hair out fixing bugs.

A: Once I was working on bugfixing on a then famous Windows 3.1 Presentation software.
I had a bug which, when it occurred, caused the Blue Screen of Death.
The bug only occurred when a certain loop had been executed over 1000 times. I used the advanced features of the debugger to let a break point pass 1000 times and then I carefully stepped through the program. Every time I went too far or skipped over a function call which contained the bug Windows Blue Screened.
Finally, after several days of work, I narrowed it down to a function that was running out of memory and instead of displaying an error message, appended the error message to a buffer. With every subsequent iteration it trashed more memory until something crucial was overwritten and Windows was trashed.
Debugging skills and perseverance was the solution.


text:
Q: How to use Predict.lm in r to reverse the regression I have some data in a dataframe calvarbyruno.1 with variables Nominal and PAR that represent the Peak Area Ratio (PAR) found from analysis of a set of standards using a particular analytical technique, and two lm models of that data (linear and quadratic) for the relationship PAR ~ Nominal.  I'm trying to use the predict.lm function to back calculate Nominal values, given my PAR values, but both predict.lm and fitted seem to only give me PAR values.  I'm slowly loosing my mojo, can anyone help ?
calvarbyruno.1 dataframe
structure(list(Nominal = c(1, 3, 6, 10, 30, 50, 150, 250), Run = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor"),
    PAR = c(1.25000000000000e-05, 0.000960333333333333, 0.00205833333333334,
    0.00423333333333333, 0.0322333333333334, 0.614433333333334,
    1.24333333333333, 1.86333333333333), PredLin = c(-0.0119152187070942,
    0.00375925114245899, 0.0272709559167888, 0.0586198956158952,
    0.215364594111427, 0.372109292606959, 1.15583278508462, 1.93955627756228
    ), PredQuad = c(-0.0615895732702735, -0.0501563307416599,
    -0.0330831368244257, -0.0104619953693943, 0.100190275883806,
    0.20675348710041, 0.6782336426345, 1.04748729725370)), .Names = c("Nominal",
"Run", "PAR", "PredLin", "PredQuad"), row.names = c(NA, 8L), class = "data.frame")

Linear Model
summary(callin.1)

Call:
lm(formula = PAR ~ Nominal, data = calvarbyruno.1, weights = Nominal^calweight)

Residuals:
       Min         1Q     Median         3Q        Max
-0.0041172 -0.0037785 -0.0003605  0.0024465  0.0071815

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.007083   0.005037  -1.406   0.2093
Nominal      0.005249   0.001910   2.748   0.0334 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.004517 on 6 degrees of freedom
Multiple R-squared: 0.5572,     Adjusted R-squared: 0.4835
F-statistic: 7.551 on 1 and 6 DF,  p-value: 0.03338

Quadratic Model
> summary(calquad.1)

Call:
lm(formula = PAR ~ Nominal + I(Nominal^2), data = calvarbyruno.1)

Residuals:
        1         2         3         4         5         6         7         8
 0.053366  0.033186  0.002766 -0.036756 -0.211640  0.177012 -0.021801  0.003867

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)  -6.395e-02  6.578e-02  -0.972  0.37560
Nominal       1.061e-02  2.205e-03   4.812  0.00483 **
I(Nominal^2) -1.167e-05  9.000e-06  -1.297  0.25138
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.128 on 5 degrees of freedom
Multiple R-squared: 0.9774,     Adjusted R-squared: 0.9684
F-statistic: 108.2 on 2 and 5 DF,  p-value: 7.658e-05

But Predict gives me these values, which both seem wrong (although I can't work out what it's doing that's different for the second set ?
> predict(callin.1)
           1            2            3            4            5            6
-0.001834123  0.008663451  0.024409812  0.045404959  0.150380698  0.255356437
           7            8
 0.780235132  1.305113826
> predict(callin.1,type="terms")
      Nominal
1 -0.32280040
2 -0.31230282
3 -0.29655646
4 -0.27556131
5 -0.17058558
6 -0.06560984
7  0.45926886
8  0.98414755
attr(,"constant")
[1] 0.3209663

EDIT: As has been pointed out, I've not been very clear on what I'm trying to achieve, so I'll try to exaplian myself better.
The data is from analysis of a set of standards of known concentrations (Nominal) which gives a particular set of responses, or peak area ratio's (PAR).  I want to show which model best fits this data to use to then analyse unknown samples to find their concentration.
I'm trying to follow someone else working for this, which involves;
a) Find the appropriate weight to use, by finding the within run variance of PAR and fitting that to a model of log(Variance(PAR))=a+blog(Nominal), where B will be the weight to use (rounded to nearest integer)
  b) Fit the data for each run to a linear model (PAR = a+bNominal) and a Quadratic Model (PAR = a+BNominal+cNominal^2)
  c) Back calculate the found concentration for each standard and compare to the Nominal conentration to give the bias
  d) Assess bias across the calibration range and pick the model based on the bias
This question is trying to do c).  Posts to the R mailing list suggest it's not appropriate to just do the regression with the terms reversed, I can manually do the calculation for the linear model, but am struggling with the quadratic model.  It seems from searcing the R mailing list that others want to do the same thing.

A: OK, I actually had to try this, after looking at various things I wrote a function to find the roots of a quadratic equation.
invquad<-function(a,b,c,y,roots="both", xmin=(-Inf), xmax=(Inf),na.rm=FALSE){
#Calculate the inverse of a quadratic function y=ax^2+bx+c (ie find x when given y)
#Gives NaN with non real solutions
root1<-sqrt((y-(c-b^2/(4*a)))/a)-(b/(2*a))
root2<--sqrt((y-(c-b^2/(4*a)))/a)-(b/(2*a))
if (roots=="both") {
    root1<-ifelse(root1<xmin,NA,root1)
    root1<-ifelse(root1>xmax,NA,root1)
    root2<-ifelse(root2<xmin,NA,root2)
    root2<-ifelse(root2>xmax,NA,root2)
    result<-c(root1,root2)
    if (na.rm) result<-ifelse(is.na(root1),root2, result)
    if (na.rm) result<-ifelse(is.na(root2),root1,result)
    if (na.rm) result<-ifelse(is.na(root1)&is.na(root2),NA,result)
},roots="both"
if (roots=="min")
    result<-pmin(root1,root2, NA.rm=TRUE)
if (roots=="max")
    result<-pmax(root1,root2, NA.rm=TRUE)
result
}

so, given the original data
> PAR
[1] 0.0000125000 0.0009603333 0.0020583333 0.0042333333 0.0322333333 0.6144333333
[7] 1.2433333333 1.8633333333
> Nominal
[1]   1   3   6  10  30  50 150 250

we can do the analysis, find the co-efficients and then find the inverse, using some sensible limits for what Nominal values we expect back...
lm(PAR~Nominal+I(Nominal^2))->bob
> bob[[1]][[3]]
[1] -1.166904e-05 # Nominal^2
> bob[[1]][[2]]
[1] 0.01061094 # Nominal
> bob[[1]][[1]]
[1] -0.06395298 # Intercept
> invquad(bob[[1]][[3]],bob[[1]][[2]],bob[[1]][[1]],y=PAR,xmin=-0.2,xmax=300,na.rm=TRUE)
[1]   6.068762   6.159306   6.264217   6.472106   9.157041  69.198703 146.949154
[8] 250.811211

Hope this helps....


text:
Q: Is there a good resource of css snippets? Usually when you design a website you don't want to take apart a complete css or fiddle around with the basic css buldingblogs.
Is there a good resource of basic building blocks for css. Something like different Menus, Page effects, and basic layouts that is written in clean code and can be easily combined together?

A: http://snipplr.com/popular/language/css
http://www.1stwebdesigner.com/development/useful-css-snippets/
http://css-tricks.com/snippets/
These sites I find helpful when I am trying to find css snippets.  Should be well over 500 snippets there.

A: http://www.smashingmagazine.com/tag/css/
http://www.alistapart.com/
... and many more.


text:
Q: Simple program for making shifts My dad asked me to make a program for him that will randomly take a name, surname etc. from Excel (or CSV file) and assign employees to the work. Each person must be at work minimum once and maximum 4 times a month. Program output should look like this:

Day 1: John Smith, James Smith Day 2: Charlie Smith, Thomas Smith

And this is how my code looks like right now
public static void main(String[] args) {

    String FileName = "excel.csv";

    File f = new File(FileName);
    String read = "";

    Map<Integer, Surname>SurnameArray = new HashMap<Integer, Surname>();

    try {
        Scanner scanner = new Scanner(f);
        while(scanner.hasNextLine()) {
            read = scanner.nextLine();
                String[] arraySplit = read.split(",");
                int kod = Integer.parseInt(tablicaSplit[0]);
                String rank = tablicaSplit[1];
                String name = tablicaSplit[2];
                String surname = tablicaSplit[3];

                SurnameArray.put(kod, new Nazwiska(kod, rank, name, surname));
                SurnameArray.get(kod).getAll();

        }
    } catch (FileNotFoundException e) {
        System.out.println("No file!");
    }

}

}
And the second class looks like this:
Class Surnames {
private int kod;
private String rank;
private String name;
private String surname;

public Surnames(int kod, String rank, String name, String surname) {
    super();
    this.kod = kod;
    this.rank = rank;
    this.name = name;
    this.surname = surname;
}

    public void getAll() {
        System.out.println(rank + " " + name + " " + surname);
    }

    public int getKod() {
        return kod;
    }

    public void setKod(int kod) {
        this.kod = kod;
    }

    public String getRank() {
        return rank;
    }

    public void setRank(String rank) {
        this.rank = rank;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setNazwisko(String surname) {
        this.surname = surname;
    }

}

I'm stuck at this moment. I think that this code is more complicated than it should be. If someone could show me how can i make it or maybe there is simpler way to make something like this.

A: I would do it this way:
    class Surnames{

         private final HashSet<String> EMPLOYEES;
         private ArrayList<String> positions;

         Surnames(String csv){
             HashSet<String> tempEMPLOYEES = new HashSet<>();
             ArrayList<String> tempPositions = new ArrayList<>();
             /*here the code for putting csv data ino an tempEMPLOYEE hashSet, or a static setter method doing this, as well for tempPositions, containing array list of positions remember to check
               if the hashset's size is equal or lower than arrayList's*/
             EMPLOYEES = tempEMPLOYEES;
             positions = tempPosition;
         }

         public void printShift(){

              for(int i = 0; i < EMPLOYEES.size(); i++){
                   System.out.println(positions.get(i) + "- " + EMPLOYEES.get(i));
              }
         }

      }

Since hashSet gives different object position in the set every single run of the program, placing EMPLOYEES to positions will be random. I mentioned checking that HashSet EMPLOYEES should be less size than positions. I iterate on the hashset- every employee should get a position.