text:
Q: Can't run any PHP I run a fairly popular website (I do not mean to brag, but I have 20,000 users who want access. I don't want to keep them waiting any longer.) and it has been down for almost a month while I try to find out what is wrong. Basically, I can't run any PHP. It all happened after we moved my account to a CPanel so I could manage things myself without the help of my web admin. I love having CPanel access, but I can't run any php.
I have re-uploaded the site, restored the 1.3TB database, made new subdomains, changed ownership, fixed permissions, made everything perfect in CPanel. Still, I only get a 500 error when running the site. No PHP works at all, not even a simple echo.
I made new .php files and tried and still no go. When I run the site in WAMP and XAMPP it works (I guess) I don't see the site, it just complains about the database not found because the $database variable is set for localhost.
My web admin and I have tried EVERYTHING. HTML works fine. I am pretty much stuck here. If you want to see the 500 error for yourself: capecraft.capturedhdtv.com/capes/site/demo.php.
Any solutions would be VERY appreciated. Also, we have tried things like remove .htaccess.
Also, my logs tell me absolutely NOTHING AT ALL. The error_log in FTP tells me just mistakes I made a long time ago during setup, like 404.shtml not existing because I forgot to copy it. The Error Log in cpanel tells me nothing relating to my issue. Just how files don't exist that people are trying to access, example a picture that isnt on the server (not
relating to the website at ALL)
CPanel Log:
Where you see .png and a missing IP, or part of a directory, I removed it for security purposes.
[Fri Feb 24 03:35:14 2012] [error] [client ] File does not exist: /home//public_html/capes2/404.shtml
[Fri Feb 24 03:35:14 2012] [error] [client ] File does not exist: /home//public_html/capes2/.png
[Fri Feb 24 03:35:13 2012] [error] [client ] File does not exist: /home//public_html/capes2/404.shtml
[Fri Feb 24 03:35:13 2012] [error] [client ] File does not exist: /home//public_html/capes2/.png
[Fri Feb 24 03:35:10 2012] [error] [client ] File does not exist: /home//public_html/500.shtml
[Fri Feb 24 03:35:10 2012] [error] [client ] SoftException in Application.cpp:357: UID of script "/home//public_html/capes/site/sup/tests/action-acceptance.php" is smaller than min_uid
[Fri Feb 24 03:35:09 2012] [error] [client ] File does not exist: /home//public_html/capes2/404.shtml
[Fri Feb 24 03:35:09 2012] [error] [client ] File does not exist: /home//public_html/capes2/.png
[Fri Feb 24 03:35:09 2012] [error] [client ] File does not exist: /home//public_html/capes2/404.shtml
[Fri Feb 24 03:35:09 2012] [error] [client ] File does not exist: /home//public_html/capes2/.png
[Fri Feb 24 03:35:06 2012] [error] [client ] File does not exist: /home//public_html/capes2/404.shtml
[Fri Feb 24 03:35:06 2012] [error] [client ] File does not exist: /home//public_html/capes2/J.png
[Fri Feb 24 03:35:01 2012] [error] [client ] File does not exist: /home//public_html/capes2/404.shtml
[Fri Feb 24 03:35:01 2012] [error] [client ] File does not exist: /home//public_html/capes2/.png
[Fri Feb 24 03:34:57 2012] [error] [client ] File does not exist: /home//public_html/capes2/404.shtml

A: Honestly? Hire someone to manage your server.  If you have a 1.3 TB database, cPanel is not for you.  Given the amount of data, you're going to need a pretty optimized MySQL server in order to get anywhere near acceptable performance.  cPanel is not exactly ideal for very large websites (it severely limits the amount of serverside settings you can change without breaking other things).
However, your actual problem is probably file permissions.  cPanel configures PHP in a way where it won't run if permissions are too open (this is a perfectly reasonable thing to do on a shared server, which is what cPanel is designed for). CHMOD all your files to 644 and all directories to 755 (see http://djlab.com/2009/06/cpanel-suphp-chmod-all-files-644-and-all-folders-755/ )

A: your whm has a settings called minimum uid the default value for it is 500
and in linux every user has a unique number called uid once you creating an account to use the cpanel for example fareed this account uid will be 500 and the next time will be set to 501 and so. for any user you can check the user uid using this ssh command:
id -u username

for a security reason whm configured apache server to not execute any php script in a file has an owner with a uid less than the minimum uid witch is set to 500 in whm.
so if you upload your site files using scp/ftp using the root user for example all these files ownership is set to root,so check this user uid if its less than 500 (btw root user uid is 0 by default) change the owner uid to something more than 500 using this ssh command:
usermod -u 1000 username

or change the files ownership to another user using  this ssh command:
 chown -R username:username  /home/username/public_html/

A: A simple way to first check whether the PHP interpreter is working correctly is by running it on the command line,
php yourphpscript.php

If the above command throws the output of the script then it's pretty much confirmed that your PHP interpreter is working fine.
Secondly, the internal server error definitely will get logged into the Apache error_log. The snippet you've provided does not seem to indicate any instance of the internal server error.
A better approach would be to run a tail with the -f option to follow the log file, then access your website URL. Any error/message that gets logged would show up on the screen,
tail -f /path/to/apache/error_log

A 500 Internal Server Error can also occur due to an incorrect entry in .htaccess.


text:
Q: preg_match_all undefined offset notice encountered I am trying to come up with a general expression which would return the string "logo = ..." for example in this case "logo = Yahoo! logo.svg" but would like it to return the complete string from the "l" in logo until the "|".
Currently I'm getting and error: Notice: Undefined offset: 0 when clicking submit. Please see script below:

Search

<form method="post">
Search: <input type="text" name="q" value="Yahoo!"/>
<input type="submit" value="Submit">
</form>

<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];

$url_2 = "http://en.wikipedia.org/w/api.php?
action=query&prop=revisions&rvprop=content&format=json&titles=$search&rvsection=0&continue=";
$res_2 = file_get_contents($url_2);
$data_2 = json_decode($res_2);

?>

Search results for '<?php echo $search; ?>'

<?php foreach ($data_2->query->pages as $r):

?>

<?php foreach($r->revisions[0] as $a);
echo $a;

print_r(preg_match_all('/ logo += (.*)/', $a, $result, PREG_PATTERN_ORDER));
echo trim($result[0][0]);
?>

<?php endforeach; ?>

<?php
}
?>

A: print_r(preg_match_all('/ logo += (.*)/', $a, $result, PREG_PATTERN_ORDER));
echo trim($result[0][0]);

There are two errors in this sample of code. First there is a space before "logo" in the pattern. Your test string doesn't seem to have this space.
Second, when you use preg_match or preg_match_all and want to use the match result, you need to use an if statement (because if the pattern is not found, indexes of $result are not set):
if (preg_match_all('/logo += (.*)/', $a, $result)) {
    echo trim($result[0][0]);
} else {
    echo 'Not found';
}

Note too that PREG_PATTERN_ORDER is the default value of the 4th parameter of preg_match_all

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need a Powershell script to move all the Folders and sub folders inside the Root folders which are older than X days, without deleting the Root folder i have a Rootfolder-IMPFolder and in that i have folders and subfolders, now i want to move these folders and subfolders to a destination Folder- JAVFolder without deleting the Rootfolder.
I have tried
robocopy C:\IMPFolder C:\JAVFolder /Z /S /MOVE /MINAGE:"$((Get-Date).AddDays(-3).ToString('yyyyMMdd'))"
After moving all the folders and subfolders, if the root folder is empty, the rootfolder itslef is deleting


text:
Q: Use regex to extract unit number I have a list of descriptions and I want to extract the unit information using regular expression
I watched a video on regex and here's what I got
import re
x = ["Four 10-story towers - five 11-story residential towers around Lake Peterson - two 9-story hotel towers facing Devon Avenue & four levels of retail below the hotels",
     "265 rental units",
     "10 stories and contain 200 apartments",
     "801 residential properties that include row homes, town homes, condos, single-family housing, apartments, and senior rental units",
     "4-unit townhouse building (6,528 square feet of living space & 2,755 square feet of unheated garage)"]
unit=[]
for item in x:
    extract = re.findall('[0-9]+.unit',item)
    unit.append(extract)
print unit

This works with string ends in unit, but I also strings end with 'rental unit','apartment','bed' and other as in this example.
I could do this with multiple regex, but is there a way to do this within one regex?
Thanks!

A: As long as your not afraid of making a hideously long regex you could use something to the extent of:
compiled_re = re.compile(ur"(\d*)-unit|(\d*)\srental unit|(\d*)\sbed|(\d*)\sappartment")
unit = []
for item in x:
    extract = re.findall(compiled_re, item)
    unit.append(extract)

You would have to extend the regex pattern with a new "|" followed by a search pattern for each possible type of reference to unit numbers.  Unfortunately, if there is very low consistency in the entries this approach would become basically unusable.
Also, might I suggest using a regex tester like Regex101.  It really helps determining if your regex will do what you want it to.


text: Q: Tilted Dirac cones and Lorentz invariance New materials called Type II Dirac semi-metals have been discovered. They have a tilted Dirac cone instead of the straight linear dispersion. These particles are said to break Lorentz invariance. How is the Lorentz invariance broken when there is a tilt in the Dirac cone?


text:
Q: Make a countdown timer where time stored is in a variable I have a variable in JavaScript storing time. For example, duration is a variable that stores time in minutes and hours as in 14 minutes or 1 hour 20 minutes. How do I make a countdown timer using this variable in JavaScript?

A: One way to do it would be to extract the desired values with a regular expression and to use setInterval() to call a function to periodically update the timer.
The following expression matches your pattern :
/^\s*(?:(\d+)\s+hour(?:s)?\s*)?(\d+)\s+minute(?:s)?$/i

The first capture group will give you the number of hours and the second one the number of minutes. You can access them thanks to the match method. That will return you an array containing the matches with one item per match (or null if no match is found).
You can then get  h and m, respectively the number of hours and the munber of minutes like this
time  = "1 hour 10 minute";
match = time.match(/^\s*(?:(\d+)\s+hour(?:s)?\s*)?(\d+)\s+minute(?:s)?$/i);

if(match)
{
  h = (match[1] === undefined) ? 0 : match[1]; // The number of hours
  m = (match[2] === undefined) ? 0 : match[2]; // The number of minutes
}

That will give you the time you want to wait. You can easily convert it into milliseconds (because its more handy) and update it every seconds for example until it reaches 0.
The setInterval() javascript function allow you to call a function (your update function) every x milliseconds. This function returns an identifier that you can store and pass later to the clearInterval() function to clear a timer previously set.
interval = h * 3600000 + m * 60000; // the interval in ms
stopTime = new Date((new Date()).getTime() + interval); // when to stop counting

counter = setInterval(count, 1000);

Your count function then just has to get the current time, update the interval and check if this one is lower or equal to 0 in order to stop the timer.
function count()
{
  now      = new Date();
  interval = Math.max(0, stopTime.getTime() - now.getTime());

  if(interval <= 0) clearInterval(counter);
}

Here is an example of such a timer.


text:
Q: Turtle Graphics - Retrieve Color of Overlapping Shapes I have a red star partially inscribed within a purple square that contains an orange circle. I am extracting the color of the point that the user clicks on. When I click on the circle inside the square, the color that is returned is purple, not orange. The program also returns purple when I click on the part of the red star that is inside the square. How can I rectify this issue? Thank you.
import turtle

def border(height,color):

    height = float(height)
    length = height *(1.9)
    length = round(length,2)

    # Draws a rectangle.
    turtle.begin_fill()
    turtle.color(color)
    turtle.down()
    turtle.forward(length)
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(length)
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.end_fill()

def big_shape(vertices, steps, length):
    turtle.color("red")
    turtle.begin_fill()
    for i in range(vertices):
        turtle.forward(length)
        turtle.right(steps*360.0/vertices)
    turtle.end_fill()

def textbox_click(rawx,rawy):
    turtle.up()
    turtle.setposition(rawx,rawy)
    turtle.down()
    rawy = -rawy
    canvas = turtle.getcanvas()
    canvas.pack(fill="both", expand=True)
    ids = canvas.find_overlapping(rawx, rawy, rawx, rawy)
    if ids: # if list is not empty
        index = ids[0]
        color = canvas.itemcget(index, "fill")
        if color != '':
            print(color.lower())

def getcoordinates():
    turtle.onscreenclick(turtle.goto)
    turtle.onscreenclick(modifyglobalvariables) # Here's the change!
    turtle.onscreenclick(textbox_click)

def modifyglobalvariables(rawx,rawy):
    global xclick
    global yclick
    xclick = int(rawx//1)
    yclick = int(rawy//1)
    print(xclick)
    print(yclick)

def main():
    border(150,"purple")
    turtle.begin_fill()
    turtle.down()
    turtle.color("purple")
    turtle.up()

    # Creates the big shape

    x1=150
    y1=3
    turtle.setposition(x1,y1)
    big_shape(5,2,50)
    turtle.begin_fill()
    turtle.down()
    turtle.up()

    # Circle
    x1=70
    y1=-107
    turtle.setposition(x1,y1)
    turtle.begin_fill()
    turtle.circle(50)
    turtle.color("orange")
    turtle.end_fill()

    getcoordinates()

    turtle.done()
main()

A: I suggest a different approach to this problem.  Rather than use tkinter underpinnings to find the color of inactive objects (from turtle's perspective), I recommend you work completely within turtle and make the drawn objects active.  We can do this by making each drawing a turtle cursor so that we're clicking on turtles, and interrogating their color, which is a simpler problem:
import turtle

def rectangle(height):
    length = height * 2

    turtle.begin_poly()
    for _ in range(2):
        turtle.forward(length)
        turtle.right(90)
        turtle.forward(height)
        turtle.right(90)
    turtle.end_poly()

    return turtle.get_poly()

def star(vertices, steps, length):
    angle = steps * 360.0 / vertices

    turtle.begin_poly()
    for _ in range(vertices):
        turtle.forward(length)
        turtle.right(angle)
    turtle.end_poly()

    return turtle.get_poly()

def circle(radius):
    turtle.begin_poly()
    turtle.circle(radius)
    turtle.end_poly()

    return turtle.get_poly()

def display_color(turtle):
    print(turtle.fillcolor())

def main():
    # Use the "default" turtle to draw the others
    turtle.penup()
    turtle.hideturtle()
    turtle.setheading(90)
    turtle.speed('fastest')

    screen.register_shape('rectangle', rectangle(150))
    screen.register_shape('star', star(5, 2, 50))
    screen.register_shape('circle', circle(50))

    rectangle_turtle = turtle.Turtle('rectangle')
    rectangle_turtle.penup()
    rectangle_turtle.color('purple')
    rectangle_turtle.onclick(lambda x, y: display_color(rectangle_turtle))

    star_turtle = turtle.Turtle('star')
    star_turtle.penup()
    star_turtle.setposition(150, 3)
    star_turtle.color('red')
    star_turtle.onclick(lambda x, y: display_color(star_turtle))

    circle_turtle = turtle.Turtle('circle')
    circle_turtle.penup()
    circle_turtle.setposition(70, -107)
    circle_turtle.color('orange')
    circle_turtle.onclick(lambda x, y: display_color(circle_turtle))

screen = turtle.Screen()

main()

screen.mainloop()

Now you should be able to click on any of the filled colored areas and you'll see the name of the color printed in the console window.  (After you click on the window itself to make it active.)

A: I see two problems
First: see my code from previous question - you have to get last element ids[-1], not first ids[0], to get topmost element.
Second: you move turtle to clicked place so now turle is topmost - so you  could move mouse after you get color and then you can still use
 index = ids[-1]

or you have to get second from the end ids[-2] but then you have to check if ids has at least two elements
if len(ids) > 1:     # if list has more than only turtle
    index = ids[-2]  # get second from the end


text:
Q: MonkeyRunner NoClassDefFoundError: com/android/chimpchat/ChimpChat I got an exception while try to run MonkeyRunner.bat.
I found only this solution but its very old and with no success.
Console line:
mymonkeyrunner test.py

The Error:
Exception in thread "main" java.lang.NoClassDefFoundError: com/android/chimpchat/ChimpChat
        at com.android.monkeyrunner.MonkeyRunnerStarter.<init>(MonkeyRunnerStarter.java:60)
        at com.android.monkeyrunner.MonkeyRunnerStarter.main(MonkeyRunnerStarter.java:188)
Caused by: java.lang.ClassNotFoundException: com.android.chimpchat.ChimpChat
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 2 more

A: Shortly after posting the comment, I figured it out. After fixing the Chimp issue, there were more libraries that Monkeyrunner was not able to find. In the end, it seemed easier to do the following:
You probably have your $ANDROID_SWT set to something like sdk_dir\tools\lib\x86_64. Copy your ANDROID_SWT\swt.jar into sdk_dir\tools\lib and then set $ANDROID_SWT to sdk_dir\tools\lib.
After I fixed this issue, I had problems with Monkeyrunner not finding adb. For that, I had to replace the last line in monkeyrunner.bat from
call "%java_exe%" -Xmx512m "-Djava.ext.dirs=%frameworkdir%;%swt_path%" -Dcom.android.monkeyrunner.bindir=..\framework -jar %jarpath% %*
to
call "%java_exe%" -Xmx512m "-Djava.ext.dirs=%frameworkdir%;%swt_path%" -Dcom.android.monkeyrunner.bindir=..\..\platform-tools -jar %jarpath% %*
Basically, make sure that -Dcom.android.monkeyrunner.bindir points to where adb.exe is sitting. Now it seems to be working.


text:
Q: Overriding assignment of value in Lua I am using Lua v5.2.2 within a C application (embedded environment/MCU).
I need to expose some "parameters" in Lua, that for reading and writing you need to directly access the hardware (thus a C call is needed). I am looking however for other means to implement this than using plain old getters and setters.
I am mostly exploring the meta-programming power of Lua, but also I believe I can create a simpler interface for the user.
What I want to achieve is behaviour like the following:
my_param = createParameter{name="hw_param1", type="number", min=0, max=100}

my_param = 5

result = my_param + 3

On the first line a new parameter is created. This is a call towards a C function. Userdata is pushed to stack with a properly initialized struct. The hardware is also initialized as needed. A new table is returned.
On the second line an assignment is done to the parameter object. I want this to call a C function with a single argument (that of the assignment), so the value can be stored to the hardware registers.
On the third line the parameter is read. I again need a call towards a C function that will get the value of the parameter from the hardware registers, and that will return the result.
Note that the actual value of this parameter may change outside the scope of Lua, so reading the value once during initialization is not correct. The C function must be called each time to get the actual value. Similarly writing to the value must cause an immediate write to the hardware.
How can I accomplish this? Specifically can I alter the metatable of the parameter to achieve lines 2 and 3? (I am aware of how to implement line 1).
Also is it necessary to return a table from the constructor? May I, for example, return a primitive Lua type (e.g. a number) that will behave like above?

A: Yes, you can modify the metatable metamethods.
Line 2 would completely change the variable's value that it holds.
However, if you were to set a field in the parameter object like: my_param.x = n, the __newindex metamethod would get invoked; which you could overwrite the metamethod to behave as you would like. In your case you would make it set the parameter's field and update it with a C function call.
Regarding line 3, same principle applies, instead this time you would just use the __add metamethod, and manipulate the object when __add is invoked.
http://lua-users.org/wiki/MetamethodsTutorial

A: This isn't exactly what you're asking for, but it's close:
function createParameter(t)
  param = {}
  param.data = t
  backingTable = {}
  metatable = {}
  function metatable.__index(t, k)
    -- You can intercept the value here if you
    -- want and pass it on to your C fuction.
    return backingTable[k]
  end
  function metatable.__newindex(t, k, v)
    -- You can intercept the value here if you
    -- want and pass it on to your C fuction.
    backingTable[k] = v
  end
  setmetatable(param, metatable)
  return param
end

--------------------------------------------------------

my_param = createParameter{name="hw_param1", type="number", min=0, max=100}

my_param.value = 5

result = my_param.value + 3

print(result) -- prints 8
print(my_param.data.name) -- prints hw_param1

You might be able to do something tricky by assigning a metatable to the global table _G, but I think that would be kind of tricky to get set up right and could lead to unexpected outcomes.
Edit:
If you really hate having to have a level of indirection, and you really want to be able to set it directly, here's how you can do it by setting the global table.
globalMetatable = {}
globalParamNames = {}
globalParams = {}
function globalMetatable.__index(t, k)
  if globalParamNames[k] then
    -- You can intercept the value here if you
    -- want and pass it on to your C fuction.
    print("Read from param " .. k)
    return globalParams[k]
  else
    rawget(_G, k)
  end
end
function globalMetatable.__newindex(t, k, v)
  if globalParamNames[k] then
    -- You can intercept the value here if you
    -- want and pass it on to your C fuction.
    print("Wrote to param " .. k)
    globalParams[k] = v
  else
    rawset(_G, k, v)
  end
end
setmetatable(_G, globalMetatable)

function createParameter(t)
  globalParamNames[t.varname] = true
end

--------------------------------------------------------

createParameter{varname="my_param", name="hw_param1", type="number", min=0, max=100}

my_param = 5

result = my_param + 3

print(result) -- prints 8
print(my_param) -- prints 5


text:
Q: Получение данных от пользователя input-form Vue Есть шаблон, который отображает данные в виде
. В нем есть кнопка, которая отображает впадающее окна с формой. Данные из формы изменяют объект data, за счет чего происходит ререндер.
Мой шаблон:

      {{ worker.name }}
      {{ worker.profession }}
      {{ worker.age }}
      <button v-on:click="showDialog()">Update info</button>

    <form v-if="toggleDialog">
      <input id="input-name" placeholder="enter name..."/>

      <input id="input-profession" placeholder="enter profession..."/>

      <input id="input-age" placeholder="enter age..."/>
      <button v-on:click="submitChanges()">Submit changes</button>
   </form>

Сам код:
new Vue({
  el: '#app',
  data: {
    toggleDialog: false,
    workers: [
      {
        name: 'Andrew',
        profession: 'Engineer',
        age: 22
      }
    ]
  },
  methods: {
    showDialog() {
      this.toggleDialog = !this.toggleDialog;
    },
    submitChanges(index) {
        event.preventDefault();
        this.workers[0].name = document.getElementById('input-name').value;
        this.workers[0].profession = document.getElementById('input-profession').value;
        this.workers[0].age = document.getElementById('input-age').value;
        this.toggleDialog = !this.toggleDialog;
    }
  }
})

Хотелось бы узнать, как можно организовать код, чтобы получать данные введенные пользователем без использования DOM или Jq в методе submitChanges?
jsfiddle

A: Это делается через v-model.

*

*Вместо v-on:click="submitChanges()" лучше использовать
@click="submitChanges".

*data должна быть функцией

*Для v-for надо всегда указывать атрибут key, в вашем случает будет: :key="index"

*В данном случает вместо v-if="toggleDialog" будет производительней использовать v-show="toggleDialog"

new Vue({
  el: '#app',
  data: () => ({
    toggleDialog: false,
    dialog: {
      name: null,
      profession: null,
      age: null
    },
    workers: [
      {
        name: 'Andrew',
        profession: 'Engineer',
        age: 22
      }
    ]
  }),
  methods: {
    showDialog () {
      this.toggleDialog = !this.toggleDialog;
    },
    submitChanges () {
      event.preventDefault();
      this.workers[0] = { ...this.workers[0], ...this.dialog };
      this.toggleDialog = !this.toggleDialog;
    }
  }
})

      {{ worker.name }}
      {{ worker.profession }}
      {{ worker.age }}
      <button @click="showDialog">Update info</button>

    <form v-show="toggleDialog" @submit="submitChanges">
      <input v-model="dialog.name" placeholder="enter name..."/>

      <input v-model="dialog.profession" placeholder="enter profession..."/>

      <input v-model="dialog.age" placeholder="enter age..."/>
      <button>Submit changes</button>
   </form>

A: Можно использовать ссылки. Про это можно почитать здесь.
<input id="input-name" ref="name" placeholder="enter name..."/>

<input id="input-profession" ref="profession" placeholder="enter profession..."/>

<input id="input-age" ref="age" placeholder="enter age..."/>

тогда
this.workers[0].name = this.$refs.name.value;
this.workers[0].profession = this.$refs.profession.value;
this.workers[0].age = this.$refs.age.value;


text:
Q: Sending data continuously through sockets I'm developing an client application which is sending the current time seconds with another application which is acting as a server. The problem is that when I run my app it is only sending the first messages (e.g. if it is 15:55:02 it starts sending 02 again and again). How can I make my app sending the time seconds continuously?
Here's my code:
public class ClientActivity extends Activity
{
    private EditText serverIp;

    private EditText sendMsg;

    private Button connectPhones;

    private String serverIpAddress = "";

    public static final int SERVERPORT = 8080;

    private boolean connected = false;

    private Handler handler = new Handler();

    private Socket socket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        serverIp = (EditText) findViewById(R.id.EditText01);
        connectPhones = (Button) findViewById(R.id.myButton);
        connectPhones.setOnClickListener(connectListener);
    }

    private OnClickListener connectListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (!connected) {
                serverIpAddress = serverIp.getText().toString();
               if (!serverIpAddress.equals("")) {
                    Thread cThread = new Thread(new ClientThread());
                    cThread.start();
                }
            }
        }
    };

    public class ClientThread implements Runnable {

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                Log.d("ClientActivity", "C: Connecting...");
                socket = new Socket(serverAddr, SERVERPORT);
                connected = true;
                Calendar c = Calendar.getInstance();
                int seconds = c.get(Calendar.SECOND);
                while (connected) {
                    try {
                        Log.d("ClientActivity", "C: Sending command.");
                        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                    .getOutputStream())), true);
                            out.println(seconds);
                            Log.d("ClientActivity", "C: Sent."+seconds);
                    } catch (Exception e) {
                        Log.e("ClientActivity", "S: Error!", e);
                    }
                }
                //Log.d("ClientActivity", "C: Closed.");
            } catch (Exception e) {
                Log.e("ClientActivity", "C: Error", e);
                connected = false;
            }
        }
    }
}

A: You must re-get the value of second every time you want to send it.

while (connected) {
            Calendar c = Calendar.getInstance();
            int seconds = c.get(Calendar.SECOND);
            try {
                Log.d("ClientActivity", "C: Sending command.");
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                            .getOutputStream())), true);
                    out.println(seconds);
                    Log.d("ClientActivity", "C: Sent."+seconds);
            } catch (Exception e) {
                Log.e("ClientActivity", "S: Error!", e);
            }
        }

A: It's because seconds is never changing.  It's outside of the loop.
Try this:
public class ClientActivity extends Activity
{
    private EditText serverIp;

    private EditText sendMsg;

    private Button connectPhones;

    private String serverIpAddress = "";

    public static final int SERVERPORT = 8080;

    private boolean connected = false;

    private Handler handler = new Handler();

    private Socket socket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        serverIp = (EditText) findViewById(R.id.EditText01);
        connectPhones = (Button) findViewById(R.id.myButton);
        connectPhones.setOnClickListener(connectListener);
    }

    private OnClickListener connectListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (!connected) {
                serverIpAddress = serverIp.getText().toString();
               if (!serverIpAddress.equals("")) {
                    Thread cThread = new Thread(new ClientThread());
                    cThread.start();
                }
            }
        }
    };

    public class ClientThread implements Runnable {

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                Log.d("ClientActivity", "C: Connecting...");
                socket = new Socket(serverAddr, SERVERPORT);
                connected = true;
                Calendar c = Calendar.getInstance();
                while (connected) {
                    try {
                        Log.d("ClientActivity", "C: Sending command.");
                        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                    .getOutputStream())), true);
                            out.println(c.get(Calendar.SECOND));
                            Log.d("ClientActivity", "C: Sent."+seconds);
                    } catch (Exception e) {
                        Log.e("ClientActivity", "S: Error!", e);
                    }
                }
                //Log.d("ClientActivity", "C: Closed.");
            } catch (Exception e) {
                Log.e("ClientActivity", "C: Error", e);
                connected = false;
            }
        }
    }
}

A: You have to flush the stream before sending another message through socket, this should help:
out.println(seconds);
out.flush();


text:
Q: parse instagram json with gson Trying to parse the following simple json response from instagram with gson but I get back "com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 21":
{provider_url: http://instagram.com/, media_id: \"312873405259835666_223937937\", title:         \"#summer\", url: http://distilleryimage2.instagram.com/d4e0e83021cc11e2b74c22000a9f1427_7.jpg, author_name: \"kajsataskinen\", height: 612,width: 612,version: \"1.0\",author_url: http://instagram.com/, author_id: 223937937,type: \"photo\",provider_name: \"Instagram\"}

If I enclose the http links in double quotes it works fine.
Any ideas?
You can get an instagram json response here: http://instagram.com/api/v1/oembed/?url=http://instagr.am/p/RXjLRULekS/
Thanks

A: Two things I can see.

*

*What you posted as the response is not actually what it responded with

*The string there is escaped, probably messing something up.

A: As for me the response is correctly escaped and "-ed:
{"provider_url":"http:\/\/instagram.com\/","media_id":

Apparently in the string you receive the escaping is missing.. How do you get it?


text:
Q: octave libs not linking properly I built octave-4.4.0 and created binaries and libs in my own path instead of /usr/local, and i am able to link my cpp program through CMakeList and its working fine.
the same octave folder when i shipped to different ubuntu in another machine and try linking the cpp program as same way through CMakeList i am unable to do execute the binary. i am getting this error. I moved octave by tar (with symlink)

error: feval: function 'pkg' not found terminate called after throwing
  an instance of 'octave::execution_exception'

please help me to resolve this


text:
Q: How to enable all users to access arduino card? I am trying to set up Linux (Debian 9) machines in a computer lab to let users plug in their arduino interface and flash their device with their code.
I do not really know about arduino and so on, and my arduino users do not know about linux. I also have never really done things with udev.
I am inspecting the script in the arduino IDE distro. It creates udev rules which I think are aimed at populating /dev with devices when a range of arduino-compatible interfaces are plugged in.
The devices belong to specific user groups and the scripts adds the current user to said groups to make things work. Now, I need all people who use these machines to be able to use arduino, but I do not want to add them all to the groups (this would require changing the ldap config which is out of my realm).
I am tempted to tweak the udev rules in the scripts to set the devices to mode 666 instead of 660.
Is this a reasonable way to achieve what I want ?
(also, if you think letting all users have access is a terrible idea, please say so and explain ; I assume that the arduino card is just a serial-like peripheral so it cannot per se do more harm to the system than a keyboard but I may be wrong)


text:
Q: how do i get my string from the class initialization? my class starts with
 public LateReturn(string username)
    {
        InitializeComponent();
    }

I've already tried things like string s = this.username/username
how do I get username
to the class, aka how can I do string s = username


text:
Q: How to stabilize cyclic tridiagonal matrix algorithm? I've received a task which is:
Solve equation by cyclic tridiagonal matrix algorithm:
$$ \frac{\partial{f}}{\partial{t}} = \lambda*\frac{\partial{f}}{\partial{x}},
\\ x\in[0,1]\ t\in[0,1]
\\ f(t=0,x) = \phi(t)
\\ f(t,x = 0) = f(t,x=1)$$
So, I've chosen the inverted triangle scheme and approximated derivatives like this:
$$\frac{f((m+1)*\tau, n*h) - f(m*\tau, n*h)}{\tau} = \lambda\frac{f((m+1)*\tau, (n+1)*h) - f((m+1)*\tau, (n-1)*h)}{2h},\ where$$
$\tau=\frac{t_{max} - t_{min}}{M}$, $h=\frac{x_{max} - x_{min}}{N} $, and $m\in[0, M-1]$, $n\in[1, N-1]$
So far so good, that is what I found about cyclic tridiagonal matrix algorithm:
Cyclic tridiagonal matrix algorithm is applayble for such systems:
$$a_1f_N-c_1f_1+b_1f_2 = -\phi_1
\\a_if_{i-1}-c_if_i+b_if_{i+1}=-\phi_2
\\...
\\a_Nf_{N-1}-c_Nf_N+b_NF_1=-\phi_N
\\a_{i+N}=a_{i},b_{i+N}=b_{i},c_{i+N}=c_{i},f_{i+N}=f_{i}$$
Okay, let's reformulate my task:
$$\frac{-\tau\lambda}{2h}f((m-1)*\tau, n*h)-f(m*\tau, n*h) + \frac{\tau\lambda}{2h}f((m+1)*\tau, n*h) = -f(m*\tau, n*h) $$
Hooray, I have $a=\frac{-\tau\lambda}{2h},\ c=1,\ b=\frac{\tau\lambda}{2h}\ and\ \phi=f(m*\tau, n*h)$
And the next line in the book is:
Cyclic tridiagonal algorithm is only stable for $a_i>0,\ b_i>0, c_i>a_i+b_i$
Poof, my solution is wrong, because there is no way, $a_i$ and $b_i$ could be both positive or negative, because they are coefficients in $\frac{\partial f}{\partial x}$ and they always have different signs.
Nevertheless, I've implemented algorithm, and of course it did not converge. I've tried two different versions, one is cyclic tridiagonal matrix algorithm(pdf), but I've got same results.
So my question is: am I wrong? Or is my teacher wrong? Or is there a way to stabilize this algorithm for my task?
It is not one question, but I'm confused)
Thank you!

A: Okay, it was my bad. To be stable $$|c| > |a|+|b|$$ condition should be accomplished, which is entirely possible.


text:
Q: spring sftp read and write in remote without local directory I know how to read and write from SFTP location with spring-integration-sftp with below configuration:
<bean id="sftpSessionFactory"
    class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory"
    p:host="${host}"
    p:port="${port}"
    p:user="${username}"
    p:password="${password}"
    p:allowUnknownKeys="true" />

<int:channel id="sftpChannel">
    <int:queue />
</int:channel>

<int-sftp:inbound-channel-adapter
    id="sftpInboundAdapter"
    channel="sftpChannel"
    session-factory="sftpSessionFactory"
    remote-directory="${remote.dir}"
    local-directory="${local.dir}"      <-- i don't want
    auto-create-local-directory="false"
    delete-remote-files="false"
    filename-pattern="*.TXT"            <-- how to specify multiple type
    local-filter="acceptOnceFilter">
</int-sftp:inbound-channel-adapter>

<bean id="acceptOnceFilter"
  class="org.springframework.integration.file.filters.AcceptOnceFileListFilter"/>

<int:poller default="true" fixed-rate="1000" max-messages-per-poll="100" />

<int:service-activator input-channel="sftpChannel" ref="stringHandler" method="handleMessage"/>

<bean id="stringHandler" class="com.core.sftp.StringHandler"/>

I tried by removing the tag local-directory element but spring not allowing to do that, Is there a way to read and write the file without creating it in local directory?
Is there a way to specify multiple file extension types without case sensitive?

A: You can use an outbound gateway (get command with -stream option) to get the remote file as an InputStream.
Note that you are responsible for closing the session once you have read the file contents from the stream.
See the documentation here.
For a case-insensitive match on the file inbound adapter, use a regex instead of a simple pattern: filename-regex="(?i).*\.txt".
There's no pattern matching with the outbound gateway; you have to use the ls command to list the files and fetch the ones you want. The sftp sample shows how to do that.


text:
Q: Bash and jq - Find a key contained in a variable and change it's value Let's say I have the following json.
{
    "userid":334,

    "Parameters": [
        {
            "ParameterValue": "james", "ParameterKey": "name"
        },
        {
            "ParameterValue": "22", "ParameterKey": "age"
        },
        {
            "ParameterValue": "belfast", "ParameterKey": "city"
        },
        {
            "ParameterValue": "software", "ParameterKey": "career"
        }
    ]
}

I have some code which takes the JSON and extracts all of the keys and their values.
echo $my_json | jq -r '.Parameters[] | .ParameterKey + "=" + .ParameterValue' >> $OUTPUT_FILE

If I look in my output file I have something similar to this:
name=james
age=22
city=belfast
career=software

How can I find, say "career" and change it's value before it is placed in the $OUTPUT_FILE? Example below:
name=james
age=22
city=belfast
career=consultation

A: You can use the map() function:
jq -r '.Parameters | map(
           if .ParameterKey == "career" then (.ParameterValue = "foo") else . end)
       [] |  .ParameterKey + "=" + .ParameterValue'

A: jq solution:
echo $my_json | jq -r --arg career "consultation" '.Parameters[]
     | [.ParameterKey, if (.ParameterKey == "career") then $career else .ParameterValue end]
     | join("=")' > outputfile

*

*--arg career "consultation" - passing value "consultation" into jq script as a predefined variable named $career

*join("=") - join/implode key and value using = as separator

The outputfile contents:
name=james
age=22
city=belfast
career=consultation

A: Here is a solution which uses a generalization of from_entries
to convert the data to an intermediate object, object multiplication with * to update the desired keys and a function to format the output taking into account blank values.
First we assume jq will be invoked with the --argjson parameter as follows to specify the key to be replaced:
$ jq -Mr --argjson replace '{"career":"consultation"}' -f filter.jq data.json

where data.json contains the sample data and filter.jq contains the following filter:
def from_entries(k;v): map({(k):v})|add;
def format_output:     keys[] as $k | if .[$k]!="" then "\($k)=\(.[$k])" else "#\($k)=" end;

  .Parameters
| from_entries(.ParameterKey;.ParameterValue)
| . * $replace
| format_output

Sample output:
age=22
career=consultation
city=belfast
name=james

If instead we run it as
$ jq -Mr --argjson replace '{"career":""}' -f filter.jq data.json

The output is
age=22
#career=
city=belfast
name=james

Try it online!


text:
Q: Working with Template Instances My problem: I have multiple instances of the 'myTemp' template on the page. When I click on the button inside of the first instance that was created, 'remove me' is displayed in console as it should. Unfortunately, when I click on the delete button in any of the other instances of 'myTemp' I do not get 'remove me' in console. I don't understand why this is happening. How is it possible to remove each instance by clicking on it's delete button?
Thanks,
Nathan
myTemp.html
<template name="myTemp">
    <button type='button' class="btn remove">Delete</button>
</template>

myTemp.js
Template.myTemp.events({
    'click .remove': function(e){

        console.log('Remove me!');
    }
});

A: With class your code is fine but if you use id it will not be as ids are supposed to be unique on the page.


text:
Q: FP in scala Chapter 5. How does the following work I see the following example on chapter 5 in FP in scala to drive home non-strictness
   val x = Cons(() => expensive(x), tl)
   val h1 = x.headOption
   val h2 = x.headOption

and I am trying to understand how
val x = Cons(() => expensive(x), tl) works? specifically the thunk () => expensive(x), given x itself is being defined?


text:
Q: JQuery Frame UI Plugin Is there a jquery plugin or UI element which emulates the HTML frame tag? I'm looking for something with a more modern jquery look, but with the same functionality as an html frame tag.
Edit: By frame functionality, I mean having the ability to display two or three html pages in one screen with a resizable bar letting the user dynamically adjust the size of each individual page.

A: EXT is way overkill, and jumping between can be seriously confusing to those of us who mostly work in jQuery.  It's definitely not a good idea to load both as you throw one into compatibility mode.  So, a Jquery option is going to likely be the best solution here.
Jquery UI is coming out with a "layout manager" that will be ideal, but it's still in development.  So, right now third party apps are your best bet.
By far, the best solution I've seen so far is JqueryUi Layout  It gives you all that frames type layout that you will ever need and is really well written.  The one thing that I haven't ever tried on it is using separate .html files to populate areas, though I suspect if it wasn't supported you could do it via includes or AJAX.  I would argue that since this is all "front-end" type work that you could safely combine your content from separate htmls to cut down on overhead, maintenance, and confusion.
And for the record, HTML Frames are HORRIBLE.....I survived that fad (and animated gifs everywhere GAH!) and never, ever want to go back!

A: Ext JS is pretty heavyweight, but it does provide what you're looking for. Unfortunately it's not free for non-open source. An alternative would be Wijmo's splitter, which has the advantage of being more lightweight, based on jQuery, and free. Unfortunately, it's not nearly as powerful as Ext. For instance, it can only collapse in one direction. Fortunately, it doesn't appear that you require that functionality.
The only other thing I can think of off the top of my head would be to hack something together with a combination of Wijmo's Superpanel and jQuery UI's resizable module. You'd have a great deal of control over the look and feel, but you'd have to take care of the resizing logic yourself. It wouldn't be very difficult or time consuming, but it doesn't really meet your request for an off the shelf component, either.


text:
Q: The maths in "The Amazing Spider Man" I just saw the trailer for the new Spider Man movie and couldn't help but notice the image after the guy says "How did you come up with this". So here is a transcript (the last part can't be seen):
$$\eqalign{
  & \frac{{d\log \Phi }}{{dt}} = \alpha \left( {1 - g{{\left( {\frac{\Phi }{k}} \right)}^\beta }} \right)  \cr
  & \Phi  = K\sum\limits_i {\prod\limits_j {\exp \left( {\frac{{{q^j}{{\left( {1 - {E_a}} \right)}^{j - 1}}}}{{\left( {j - 1} \right)!\left( {1 - {{\left( {1 - {E_a}} \right)}^{j - 1}}} \right)}}} \right)} } \log a \cdots  \cr} $$

Does it resemble, make sense, relate to any real math? (I dont really see any $i$ index inside the expression for example).
I actually laughed at the sigma, pi, exp triad.


text:
Q: TFVC: checkout to specific changeset, make new changes, and go back to head with new changes Title pretty much says it all. Imagine if I have the following changesets:
changeset 1
changeset 2 -> here is where I need to make a new change
changeset 3
changeset 4

Now I want to do this:
changeset 1
changeset 2
changeset 2'* <- new changes
changeset 3
changeset 4 <- has my new changes

I don't care if any other methods can achieve the same thing. If you have anything in mind, I would love to hear that. Thanks for your time!
I have tried to get specific version at changeset 2 and then checking in my new changes, but this only makes a new changeset after changeset 4. This basically kind of resets the branch to changeset 2 meaning I cannot merge the new changes back to changeset 4 and make a new changeset called 5 for example. I only have a GIT background so I'm not familiar with TFVC much. any inputs are much appreciated.


text:
Q: Conjecture: $\lim_{x\rightarrow 0_+} \sum_{n=1}^{\infty} \frac{\sin(n^2 x)}{n} = \frac{\pi}{4}$ I was playing around with sums the other day, and started fiddling with the function
$$
f(x) = \sum_{n=1}^{\infty} \frac{\sin(n^2 x)}{n}\, .
$$
Now, obviously this is a very jagged function. (I think the derivative doesn't exist anywhere.) However, it seems to go to a finite, positive limit as $x\rightarrow 0_+$. Furthermore, just looking at the first few decimal places of this limit, it looks like it may be $\pi/4$. It seems plausible that such a limit might go to a "nice" number like $\pi/4$, but I can't prove it.
A few known things about this problem:
1) $f(x)$ is odd, so $\lim_{x\rightarrow 0_{-}} f(x) = -\lim_{x\rightarrow 0_{+}} f(x)$.
2) $f(x)$ is $2\pi$-periodic (obviously).
3) One possible way that occurs to me to evaluate this limit (if it exists), is to replace it with the following:
\begin{align}
\lim_{x\rightarrow 0_{+}} f(x)
&= \lim_{x\rightarrow 0_{+}} \frac{1}{x}\int_{0}^{x} dy\, f(y)\\
&= \lim_{x\rightarrow 0_{+}} \frac{2}{x}\sum_{n=1}^{\infty} \frac{\sin^2\left(n^2 x/2\right)}{n^3}
\end{align}
The latter series is smoother and converges more quickly than the original one, so it's better-suited to numerics. If I use $x = 0.0001$ in this series and sum the first $100,000$ terms in Mathematica, I get $0.785393$, whereas $\pi/4 = 0.785398...$ I don't know where to go from there. (I tried the Poisson summation formula to no avail.)
Can anyone here prove this conjecture? Or disprove it? Or show that the question is somehow ill-posed?

A: An interesting trick is to consider that the integral of $f(x)$ against the approximate identity $m e^{-mx}$ is given by:
$$ \int_{0}^{+\infty}f(x)\,me^{-mx}\,dx=\sum_{n\geq 1}\frac{mn}{m^2+n^4} \tag{1}$$
However:
$$ \frac{2m^2 n}{4m^4+n^4} = \frac{m}{2}\left(\frac{1}{2m^2-2mn+n^2}-\frac{1}{2m^2+2mn+n^2}\right)\tag{2}$$
hence:
$$ \sum_{n\geq 1}\frac{2m^2 n}{4m^4+n^4}=\frac{i}{4}\left(H_{-m(i+1)}-H_{m(-1+i)}-H_{m(1-i)}+H_{m(1+i)}\right)\tag{3}$$
and by letting $m\to +\infty$ we get:
$$\begin{eqnarray*} \lim_{x\to 0^+}f(x) &=& \lim_{m\to +\infty}\sum_{n\geq 1}\frac{2m^2 n}{4m^4+n^4}\\&=&\frac{i}{4}\left(\log(-1-i)-\log(-1+i)-\log(1-i)+\log(1+i)\right)\\&=&\color{red}{\frac{\pi}{4}}\tag{4}\end{eqnarray*}$$
proving your conjecture through the unlimited power of the digamma function.

The same approach leads to:
$$\begin{eqnarray*} \lim_{x\to 0^+}\sum_{n\geq 1}\frac{\sin(n^3 x)}{n}&=&\lim_{m\to +\infty}\sum_{n\geq 1}\frac{m^3 n^2}{m^6+n^6}\\&=&\lim_{m\to +\infty}\frac{\pi}{6}\left(-\coth(m\pi)+\coth\left(\frac{1+i\sqrt{3}}{2}\,m\pi\right)+\coth\left(\frac{1-i\sqrt{3}}{2}\,m\pi\right)\right)\\&=&\color{red}{\frac{\pi}{6}}.\tag{5}\end{eqnarray*}$$

The reasonable conjecture:

$$\forall k\in\mathbb{Z}^+,\quad \lim_{x\to 0^+}\sum_{n\geq 1}\frac{\sin(n^{k}x)}{n}=\frac{\pi}{2k}\tag{6}$$

is left as object of further investigations.

A: OK, I think I've got an answer to this using my non-rigorous "physicist's math".
Using simple algebra, we can write
$$
\frac{\sin(n^2 x)}{n} = \frac{\sin(n^2 x)}{2\sqrt{n^2 x}\left(\sqrt{n^2 x} - \frac{1}{2}\sqrt{x}\right)}\Delta_n\, ,
$$
where $\Delta_n = n^2 x - {(n-1)}^2 x$. So our limit becomes:
$$
\lim_{x\rightarrow 0_+} f(x) =
\lim_{x\rightarrow 0_+} \sum_{n=1}^{\infty} \frac{\sin(n^2 x)}{2\sqrt{n^2 x}\left(\sqrt{n^2 x} - \frac{1}{2}\sqrt{x}\right)} \Delta_n\, .
$$
This is a kind of "warped" Riemann sum over the function
$$
g(z) = \frac{\sin(z)}{2\sqrt{z}\left(\sqrt{z} \,-\, \frac{1}{2}\sqrt{x}\right)}\, ,
$$
where $x$ is a fixed positive number:
$$
\lim_{x\rightarrow 0_+} f(x) =
\lim_{x\rightarrow 0_+} \sum_{n=1}^{\infty} g(z_n)\, \Delta_n\, .
$$
I use the word "warped" here because the "sampling points" $z_n = n^2 x$ are not evenly-spaced, but grow closer and closer together as $x\rightarrow 0_+$. $\Delta_n = z_n - z_{n-1}$ is the width of the $n^{\mathrm{th}}$ "column" of area under the graph of $g(z)$. Thus:
\begin{align}
\lim_{x\rightarrow 0_+} f(x)
&= \lim_{x\rightarrow 0_+} \int_{0}^{\infty} dz\, \frac{\sin(z)}{2\sqrt{z}\left(\sqrt{z} \,-\, \frac{1}{2}\sqrt{x}\right)}\\
&= \int_{0}^{\infty} dz\, \frac{\sin(z)}{2z}\\
&= \frac{\pi}{4}\, .
\end{align}
Obviously I did some non-rigorous things there, such as exchanging limits and integrals, so if anyone has an alternative demonstration, I'd be curious to see it.

A: I have a solution for similar problem
$$
\sum_{n=1}^{\infty} \frac{\sin(n x)}{n}\ =\frac{1}{2} i \left(\log \left(1-e^{i x}\right)-\log \left(1-e^{-i x}\right)\right)=\arctan\left(\frac{\sin (x)}{1-\cos (x)}\right)
$$
and
$$
\lim_{x\rightarrow 0_+} \sum_{n=1}^{\infty} \frac{\sin(n x)}{n} = \frac{\pi}{2}
$$


text:
Q: How do I get the default system locale in Windows 7? I want to get the default system locale in Windows 7, I figured out that the login screen uses this. So I want to start one application during system startup, before the login screen appear. So that the result I get is user independent. Please let me know if any have pointers...

A: You don't necessarily need to run this from the login screen, an example:
systeminfo /FO LIST | find "System Locale"

A Developer alternative can be found here: MSDN - GetSystemDefaultLocaleName
This result will be user independent!
Don't use a service just to get that value, services are meant to be long-running tasks.
Don't use credential providers either, they are used as authentication methods.

A: I do know Windows 7 introduces Trigger Startup Services which allows you to start services without requiring a user to log into the console.  Hopefully this might point you in the right direction:
http://windowsteamblog.com/blogs/developers/archive/2009/10/26/windows7-trigger-start-services-part-1-introduction.aspx


text:
Q: Olympiad problem - last $3$ digits of $3\times7\times11\times15\times19\times23\times...\times115\times119$ Can anyone helps me to solve this problem with full explanation or tricks pls
Find the last $3$ digits of
$$3\times7\times11\times15\times19\times23\times...\times115\times119$$
Thanks!:)

A: Firstly, the last $3$ digits of a number is the remainder when the number is divided by $1000$.
Now, one can observe that the number is divisible by $125$, since it contains $15 = 5 \times 3$, $35 = 5 \times 7$, and $115 = 5 \times 23$.
Secondly, we want to find its remainder when divided by $8$. The product contains $30$ numbers, so the remainder is equivalent to $(3 \times (-1))^{15} = (-3)^{15} = (1+8)^7 \cdot (-3) \equiv -3 \equiv 5 \pmod 8$.

It is divisible by $125$ and leaves a remainder of $5$ when divided by $8$.
By the Chinese remainder theorem (aka trial and error), its remainder when divided by $1000$ is $\fbox{125}$.

A: One thing to notice is that there are at least 3 factors of $5$ in the product, so it is a multiple of $125.$  And it is odd, so the last three digits must be one of: $125, \; 375, \; 625, \; 875.$
Second, this product is $$\prod_{n=1}^{30} (4n-1).$$
If you multiply this out, every term has a lot of $4$'s in it, except the last two. The last term is $(-1)^{30}$.  The second last term is
$$-\sum_{n=1}^{30} 4n = -4\frac{30\cdot 29}{2} = -1740$$
which is multiple of $8$ plus $4.$ So the product must be $5$ more than a multiple of $8$.  This leaves only $125$ as the answer.
We choose to look at $125$ and $8$ because this is the prime power factorization of $1000$.


text:
Q: Manipulating a scrollable div with jQuery I have a div with the following CSS properties, in order to have it scroll in place:
height: 746px;
width: 295px;
overflow: auto;
margin-bottom: 11px;
position: relative;

I need to do two seperate things with jQuery:

*

*onclick of a button, scroll the box up by 100px.

*upon reaching the bottom of the box when scrolling, fire a function.

I've tried using both .position() and .offset() to get where it is now, but neither are updating the position when it's scrolling. What am I doing wrong?

A: *

*use the scrollTop property
$(element).scrollTop($(element).scrollTop()+100);

*use the scroll event
$(element).scroll(function(){
  //check the height of the div and the scrollTop value so you know if you are at the bottom and then do some code
})


text:
Q: Node.js Express Server - Global Variable Issue To get this out of the way: I am not really posting a bug in this question!

Issue
I recently found a problem with my Node.js and Express backend code, while making multiple requests from the front end at the same time. Let's assume one of my endpoints looks like this:
var payload, id1, id2, data1, data2

exports.someFunction = async (req, res) => {
    payload = req.body.payload
    id1 = req.params.id1
    id2 = req.query.id2
    try {
        data1 = await fetchData1()
        data2 = await fetchData2()
        return responseHandler.success({ data1, data2 })
    } catch (err) {
        return responseHandler.error(err)
    }
}

async function fetchData1() {
    return new Promise((resolve, reject) => {
        // fetch data from database by accessing
        // payload, id1, id2
        // here
    })
}

The issue I discovered, was that the global variables like payload, id1, etc. were overwritten while the async functions were executed. (If the next request is made before the first one finished) Thereby some functions were executed with wrong inputs and weird responses emerged.

Solution
My solution then was to move those global variables inside the function, which resulted in a heavy usage of function arguments:
exports.someFunction = async (req, res) => {
    const payload = req.body.payload
    const id1 = req.params.id1
    const id2 = req.query.id2
    try {
        const data1 = await fetchData1(payload, id1, id2)
        const data2 = await fetchData2(payload, id1, id2, data1)
        return responseHandler.success({ data1, data2 })
    } catch (err) {
        return responseHandler.error(err)
    }
}

async function fetchData1(payload, id1, id2) {
    return new Promise((resolve, reject) => {
        // fetch data from database
    })
}

As you can see, the code gets really messy, which actually was the reason I used global variables in the first place.

My actual questions

*

*(1) Is it silly to use "global variables" in express routes?

*(2) Is there a better way of supplying other functions with data, rather than inputting all arguments every single time

*(3) Is my hypothesis correct, that those "global variables" are overwritten when a new request calls this specific route?

A:
(1) Is it silly to use "global variables" in express routes?

Global variables are indeed considered bad practice in general.

(2) Is there a better way of supplying other functions with data, rather than inputting all arguments every single time

What's wrong with inputing them every single time? The code you show seems perfectly fine to me. It's usually better for readability and testing to have the dependencies of your functions explicit.

(3) Is my hypothesis correct, that those "global variables" are overwritten when a new request calls this specific route?

Yes, javascript is executed synchronously by default, until an async/await block appears. In your example, there is no guarantee that the async block will be resolved before another request is made, which make that code very fragile.

A: *

*Depends on the usage of the global variables. If you have something that is valid for all requests but might change based on other conditions it makes totally sense to use global variables in my opinion. But for your use case it's absolutely the wrong approach as you already found out.

*No. The only alternative would be to pass an object with multiple properties instead of multiple arguments - but basically that's the same.

*Yes, since the variables are global and requests are asynchronous the variables will be overwritten each time. Depending on the amount of time your fetchData functions take your handler will use the wrong data.


text:
Q: PowerShell - Show Property of Parent Object and Child Object If I have a list of email metadata in a hashtable and each email has a hashtable with a list of attachments inside that object, like this:
$Emails = @{
            ID          = "E123";
            Subject     = "Check this out";
            Attachments = @{
                            ID   = "A123";
                            Name = "FunnyPic.jpg"
                           }
           }

And then that hashtable is converted to a PSObject like this:
$EmailsObject = New-Object -TypeName PSObject -Property $Emails

And I want to do something like this:
$EmailsObject | Select ID, Attachments.ID

How would I do that?
I want to associate the ID of the Email with the ID's of the associated attachments.

A: You will want to use calulated properties.
$Emails | Select-Object -Property @{Name='ID';Expression={$_.ID};},@{Name='AttachmentId';Expression={$_.Attachments.ID};}

You can shorten Name and Expression to n and e.
See this article for more.

A: you need to use a calculated property if you use Select-Object. something like this ...
$Emails = @{
            ID          = "E123";
            Subject     = "Check this out";
            Attachments = @{
                            ID   = "A123";
                            Name = "FunnyPic.jpg"
                           }
           }
$EmailsObject = New-Object -TypeName PSObject -Property $Emails

$EmailsObject |
    Select-Object ID,
        @{
        n = 'AttID'
        e = {$_.Attachments.ID}
        }

output ...
ID   AttID
--   -----
E123 A123


text:
Q: php mssql database query not working I need some help.  I am writing a small program to retrieve data from mssql database using php.  When I write the query on sql management studio I get a result, but when I run the same query within php I dont get any results.
the following is on init.php.  This is file containing the database connection strings
<?php

error_reporting(E_ALL);
$serverName = "SUPERMAN";

$connectionInfo = array('Database'=>'Eque', "UID"=>"develop", "PWD"=>"develop");
$conn = sqlsrv_connect($serverName, $connectionInfo);

if($conn) {
    "Connection established.
";
}else {
    "Connection could not be established.
";
    die(print_r(sqlsrv_errors(), true));
}

?>

the following is test page where the data is supposed to be displayed:
<?php
error_reporting(E_ALL);
require_once 'scripts/init.php';

$query = "SELECT a.ID AS ApnID, b.Surname, b.Initials, b.Cell, b.Email,
                            a.Deadline, a.NotifyEmail, a.NotifySMS, c.Name, a.RecvDate,a.Barcode
                        FROM dbo.Apn a
                        INNER JOIN dbo.Apt b ON a.AptID = b.ID
                        INNER JOIN dbo.Status c ON a.StatusID = c.ID";

//$params = array($id, $name);
$stmt = sqlsrv_query( $conn, $query);

$record = sqlsrv_fetch_array($stmt);
                {
                    echo $record['Surname'];
                    echo '
';
                    echo $record['Initials'];
                    echo '
';
                }

?>

I connects properly to the database, therefore I think the issue lies on the test page.  Please Assist!

A: Here
if($conn) {
    "Connection established.
";
}else {
    "Connection could not be established.
";
    die(print_r(sqlsrv_errors(), true));
}

Try this
if($conn) {
    echo "Connection established.
";
}else {
    echo "Connection could not be established.
";
    die(print_r(sqlsrv_errors(), true));
}

and this
<?php

error_reporting(E_ALL);

As
    <?php
    error_reporting(E_ALL);
   ini_set('display_errors', 1);

And this
die(print_r(sqlsrv_errors(), true));

as
die('Error: '.sqlsrv_errors());

This is no good too
$record = sqlsrv_fetch_array($stmt);
                {
                    echo $record['Surname'];
                    echo '
';
                    echo $record['Initials'];
                    echo '
';
                }

So
while(false !== ($record = sqlsrv_fetch_array($stmt)))
                {
                    echo $record['Surname'];
                    echo '
';
                    echo $record['Initials'];
                    echo '
';
                }

Or
$record = sqlsrv_fetch_array($stmt);

echo $record['Surname'];
echo '
';
echo $record['Initials'];
echo '
';


text:
Q: Updating ASP.NET Label Upon Completion of Task Ok, so I've done some searching, but I can't seem to find exactly what I'm looking for. I'm fairly new to ASP.NET, but not to C#. I had to create a page to handle a regular web services request in order to update a web store with data from a web-based accounting software service. The problem I have is that I need the page to load first, then run the update, otherwise the page times out and the update fails. The display page has only a few labels, and that's all I require on it as the page will refresh every so often and run the update. However, I need the update method to be able to put the results to the screen. I have no problem getting the update to run, just making sure the results are displayed. I have no buttons that are pressed, there are no forms used.
Here's my page code:
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="MainContent">

<asp:Localize ID="Caption" runat="server" Text="Update of Order Status From NetSuite Into AbleCommerce"></asp:Localize>

        <asp:Label ID="Label0" runat="server"></asp:Label>

        <asp:Label ID="Label1" runat="server"></asp:Label>

        <asp:Label ID="Label2" runat="server"></asp:Label>

        <asp:Label ID="Label3" runat="server"></asp:Label>

</asp:Content>

And here is my back code:
public partial class Template_Default : CommerceBuilder.Web.UI.AbleCommercePage
{
    private void PerformUpdate(object State)
    {
        Store _Store = StoreDataSource.Load(1);
        Token.Instance.InitStoreContext(_Store);
        String results = PontoonUpdate.soUpdate(); // method that performs the updates
        Label3.Text = "Update Completed. " + String.Format("{0:MM-dd-yyyy hh:mm:ss}", DateTime.Now + "\n\n" + results);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Label0.Text = "Update start time: " + String.Format("{0:MM-dd-yyyy hh:mm:ss}", DateTime.Now);
        Label1.Text = "Order updates will begin.";
        Label2.Text = "Processing...";
        if(!Page.IsPostBack)
            System.Threading.ThreadPool.QueueUserWorkItem(PerformUpdate);
    }
}

I know I'm missing something, and I know it's due to my lack of experience with ASP.NET. If anyone has any pointers I'd be greatly appreciative.

Ok, I found the answer to what I wanted to do. I was searching for something else and found this...
http://www.simple-talk.com/dotnet/asp.net/implementing-waiting-pages-in-asp.net/

A: wrap your controls in an UpdatePanel. It is a poor man's AJAX. Place your controls (or your entire page for that matter) into the content template. Then in the Triggers section, tell it which controls to watch, and what events to catch. It'll do the rest. In your case, from here you just need some sort of event to trigger. It could be a javascript to fire a button onLoad, or even the bind event of some other control. It doesn't really matter.
<asp:UpdatePanel runat="server" ID="update">
    <ContentTemplate>

<asp:Localize ID="Caption" runat="server" Text="Update of Order Status From NetSuite Into AbleCommerce"></asp:Localize>

                <asp:Label ID="Label0" runat="server"></asp:Label>

                <asp:Label ID="Label1" runat="server"></asp:Label>

                <asp:Label ID="Label2" runat="server"></asp:Label>

                <asp:Label ID="Label3" runat="server"></asp:Label>

    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="generate" EventName="Click" />
    </Triggers>
</asp:UpdatePanel>


text:
Q: HappyMapper namespace prefix error I have the following XML doc, and would like to convert the xml to object using happymapper.
<objects>
<item>
<title>book1</title>
<link>http://asdf.com</link>
<pubDate>march 1 2009</pubDate>
<description>testtesttest</description>
<media:thumbnail url='http://url.com' />
</item>
<item>
<title>book2</title>
<link>http://dffdfdf.com</link>
<pubDate>march 3 2009</pubDate>
<description>testtesttest</description>
<media:thumbnail url='http://url.com' />
</item>
</objects>

#HappyMapper object
class Item
 include HappyMapper
 namespace 'http://search.yahoo.com/mrss/'
 element :title, String
 element :link, String
 element :pubDate, String
 element :description, String
 element :media_thumbnail, String, :tag=>'media:thumbnail', :attributes=>{:url=>String}
end

items=Item.parse(xml_document)
items.each do |i|
 puts i.title
 puts i.media_thumbnail.url
end

Error: Namespace prefix media on thumbnail is not defined at :11.
Error: Namespace prefix media on thumbnail is not defined at :22.

A: *

*Check that your XML document has a namespace definition for prefix media. Element <media:thumbnail> or one of its ancestors should have a namespace definition that looks like xmlns:media="http://some.uri". If there is no namespace-uri to prefix mapping, then your XML is not (namespace) well-formed which causes the parsing to fail.

*Check that you have defined the correct namespace for the thumbnail element in the HappyMapper code.


text:
Q: Pandas: Pad data-frame to max row length I have data-frame like the following:
df = pd.DataFrame({"id": [100, 200, 200, 300, 300, 300], "val1": [1.5, 2.5, 4.5, np.nan, 6.5, np.nan], "val2": [9.5, 7.5, 8.5, 3.5, np.nan, np.nan]})

What I want to achieve is to zero pad each group (assuming that the data-frame is grouped by id), to the max number of rows for all groups. The max number of rows per id for the data-frame above is 3, so the resulting data-frame should look like the following:
df_true = pd.DataFrame({"id": [100, 100, 100, 200, 200 ,200, 300, 300, 300], "val1": [1.5, 0, 0, 2.5, 4.5, 0, np.nan, 6.5, np.nan], "val2": [9.5, 0, 0, 7.5, 8.5, 0, 3.5, np.nan, np.nan]})

Can someone point me in the right direction how to achieve that?

A: So we do with cumcount with id  then using stack and unstack
df['new']=df.groupby('id').cumcount()
df_true=df.set_index(['id','new']).unstack(fill_value=0).stack(dropna=False).reset_index('id')
df_true
Out[908]:
      id  val1  val2
new
0    100   1.5   9.5
1    100   0.0   0.0
2    100   0.0   0.0
0    200   2.5   7.5
1    200   4.5   8.5
2    200   0.0   0.0
0    300   NaN   3.5
1    300   6.5   NaN
2    300   NaN   NaN


text:
Q: A better way to inject data in controller using stateparams. I dont want url to get updated with what I pass along I am using ui routers stateparams and I need to update a view. If I pass any of the fields along with the url, I can update the view but since my json entry can have multiple key value pairs, the idea of adding every key to the url of stateProvider is not a smart Idea. So my question is how do I update the view by just passing one of the fields of JSON.
I put up a plnkr demo, if you see the url, I don't want to append all the text in the url, as it looks awkward. Please tell me what is the approach to solve this. Apparently I can't add a unique id to JSON and access it as state
http://plnkr.co/edit/1ItQLvu3O1gjROXR39QN?p=preview
.state('guy', {
    parent: 'guys',
    url: "/:id/:desc",
    controller:'MyCtrl',
    templateUrl: "file1.html",
  })

A: There is a working plunker
In case I understand your issue properly:

... need to pass parameters to state, but not via url...

we can solve it by state setting: params : {}.
This could be our new 'guy2' state definition
.state('guy2', {
    parent: 'guys',
     url: "/:urlParam",
     params: {
       urlParam: null,
       param1: null,
       param2: null,
       param3: null,
    },
    controller:'MyCtrl',
    templateUrl: "guy.html",
})

The urlParam will be part of url, while the others won't. We can call it like this:
{{guy.name}}

and for data.json like this:
[
    {

    "name":"Jane",
    "desc":"Jane descrition ...",
    "info":"Jane Info ...",
    "note":"Jane Note ..."
    },
    ...
]

we would see link like this:
#/route/Jane

Check it in action here
There are few links to some more details:

*

*Angular ui router passing data between states without URL

*How to pass parameters using ui-sref in ui-router to controller

A:
Why you not add your json an unique field and unique filed add with url. if your id field is unique then id field add with url otherwise show this code.

.state('guy', {
    parent: 'guys',
     url: "/:unique_id",
    params : {desc:null}
    controller:'MyCtrl',
    templateUrl: "file1.html",
  })


text:
Q: ArcGIS 10: Create an event linear layer from a point layer based on directionality I have a point layer that reflects the speed limits and a line layer of the roads. The location of the speed sign indicates in which direction the speed limit applies.
How can I make linear event table on top of the road layer that reflects the speeds? So for each segment, return two speed attributes, one for each direction.

A: I don't have enough rep to comment, but my question is whether or not the roads are already in segments that correspond to the speed zones, i.e. would each segment generally have 1 speed associated with it per side, or more than one.
Regardless, here's my suggestion, though it is contingent on you having a license level that would allow a one-sided buffer (advanced/ArcInfo, I believe).  A similar principal could be applied with basic tools, but would be more complex.  Also, I expect this would take a while to run...
import arcpy
def TakeOutTrash(dataset):
    if arcpy.Exists(dataset):
        arcpy.management.Delete(dataset)
roads = "path/to/roads" #make sure it's in a projected crs with meter units
buff_right = "path/to/new/buffer/feature/class1" #new gdb feature class
buff_left = "path/to/new/buffer/feature/class2" #new gdb feature class
arcpy.analysis.Buffer(roads,buff_right,6,"RIGHT","FLAT")
arcpy.analysis.Buffer(roads,buff_left,6,"LEFT","FLAT")

Now you have buffers for each side of each road, that are 6 meters from the center line, which should cover all of the signs.  You could do an easy select by location to make sure that this is the case, and if not, rerun the buffer operations with 1 or 2 extra meters.
Next:
final_dict = {}
buffers = [buff_right, buff_left]
for i, buffer in enumerate(buffers):
    rows1 = arcpy.SearchCursor(buffer)
    for row1 in rows1:
        final_dict[seg] = [[],[]]
        seg = str(row1.getValue("seg_num"))
        TakeOutTrash("fl")
        fl = arcpy.management.MakeFeatureLayer(buffer,"fl",'"seg_num" = ' + seg)
        arpcpy.management.SelectLayerByLocation(signs,"INTERSECT",fl)
        rows2 = arcpy.SearchCursor(signs)
        for row2 in rows2:
            final_dict[seg][i].append(row2.getValue("posted_speed"))

So now you have a dictionary in this format:
"seg_num":[[list of speeds on the right],[list of speeds on the left]]

from which you can do whatever you like, for example:
for k,v in final_dict.iteritems():
    print "road segment {0}:".format(str(k))
    print "   speeds on right: {0}".format(", ".join(v[0]))
    print "   speeds on left: {0}".format(", ".join(v[1]))

Or just test for how many speeds there are on each side of the segment, or write it to fields in the original roads feature class, etc. Again, not sure if this could be a final solution with the data you have, but it could certainly work as a part of it.  I could see it being used in conjunction with the snapping/splitting process described above.
To write to the roads layer, you could make two new fields, SPD_RIGHT and SPD_LEFT, and for now (unless you know for sure that there is only one speed per segment) make them text fields.  Then:
urows = arcpy.UpdateCursor(roads)
for row in urows:
    seg = row.getValue("seg_num")
    right_speeds = ", ".join(final_dict[seg][0])
    left_speeds = ", ".join(final_dict[seg][1])
    row.setValue("SPD_RIGHT",right_speeds)
    row.setValue("SPD_LEFT",left_speeds)
    urows.updateRows(row)

Of course, it's ideal to have only one speed per segment, but that goes back to the original question of how the segments are currently split.

A: For linear route event layers, you need to create a table containing the ID of the route and the start and end m-values.
If your roads don't have m-values, you can create routes using the create routes tool.
The second step is to extract the m-values of your roads for each point, which can be done with locate feature along road. If I see well on your figure, the points are located on the same side of the road if they are for the same direction. This is great because you then have a positive or negative distance that tells you on which side you are.
The easiest way to the last step is in Microsoft Excel:

*

*Sort your points by roadID and by sign of the distance to the route

*Add a new column with the m-value of the next point (or the previous point, depending on the direction).

*There will be one missing value at the end that should be filled with either 0 or the maximum m-value of the segment.

EDIT: after sorting, your table will look like this
 pointID RoadID mvalue dist speed
 15      2      25     1    80
 25      2      30     1    50
 87      2      45     12   70
 etc

You see that the points are sorted by m-values. The third column in my case would be the start of the event. the new event layer should have a from and a to field. So in my example it would look like :
pointID RoadID from to speed
15      2      25   30   80
25      2      30   45   50
87      2      45   max  70

in the other direction, it would be
pointID RoadID from to speed
15      2      0    25   80
25      2      25   30   50
87      2      30   45   70

You can then make your event layer using the sign as an offset field to locate the speed limitation on the correct side of the routes.


text:
Q: Python code working on one computer, but not other: "expected str, bytes or os.PathLike object, not list" I'm running this code to get a list of tables from Google Big Query, using subprocess and the bq command from GSUtils. For some reason that I don't understand, in one computer it works (Python 3.8.6), but in the other (Python 3.8.7) I get the error posted below.
What is wrong with the code?
Thanks!
import subprocess
import re

params=[]
params.append("--use_legacy_sql=false ")
params.append(r"SELECT table_name FROM Exportar_CSV.INFORMATION_SCHEMA.TABLES WHERE table_schema IN ('Exportar_CSV')")
process = subprocess.run(['bq','query',params], shell=True, capture_output=True)
output = process.stdout.decode("utf-8")
#Convert the output to a list type.
table_list=output.split("\r\n")
table_list=[item.strip("|").strip() for item in table_list]
table_list= [ item for item in table_list if "table_name" not in item and "+--------" not in item and '' != item]

This is the error that python throws:
Traceback (most recent call last):
  File "Export_to_CSV.py", line 8, in <module>
    process = subprocess.run(['bq','query',params], shell=True, capture_output=True)
  File "C:\Python\lib\subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Python\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Python\lib\subprocess.py", line 1247, in _execute_child
    args = list2cmdline(args)
  File "C:\Python\lib\subprocess.py", line 549, in list2cmdline
    for arg in map(os.fsdecode, seq):
  File "C:\Python\lib\os.py", line 818, in fsdecode
    filename = fspath(filename)  # Does type-checking of `filename`.
TypeError: expected str, bytes or os.PathLike object, not list

A: As Luke Woodward says, it seems to be that the argument is a list inside a list. So changing that, it worked on both.
Still don't know why it worked in one computer...
params=[]
params.append(str("bq"))
params.append(str("query"))
params.append(str("--use_legacy_sql=false"))
params.append(str(r"SELECT table_name FROM Exportar_CSV.INFORMATION_SCHEMA.TABLES WHERE table_schema IN ('Exportar_CSV')"))
process = subprocess.run(params, shell=True, capture_output=True)
output = process.stdout.decode("utf-8")
#Convert the output to a list type.
table_list=output.split("\r\n")
table_list=[item.strip("|").strip() for item in table_list]
table_list= [ item for item in table_list if "table_name" not in item and "+--------" not in item and '' != item]


text:
Q: Creating an object from a base class object in Python I have a base class:
class Animal(object):
    def __init__(self, name=None, food=None):
        self.name = name
        self.food = food

    def eat(self):
        print "The %s eats some %s" % (self.name, self.food)

And a class that extends it:
class Pet(Animal):
    def pet(self):
        print "You pet the %s." % self.name
    def feed(self):
        print "You put some %s into the bowl." % self.food
        self.eat()

Let's say I have an Animal object, created thusly:
>>> fluffy_as_animal = Animal('dog', 'kibbles')

Is there a straightforward way in python to create a Pet object from fluffy_as_animal, short of actually writing out:
>>>> fluffy_as_pet = Pet(fluffy_as_animal.name, fluffy_as_animal.food)

Update
The reason I'm doing this implementation is that I have a class with a function that returns a set of objects of type Animal all which I want to actually use as Pet objects:
class AnimalStore(object):
    def fetch(count, query=None, server=None, *args, **kwargs):
        connection = connect_to_server(server)
        resp = connection.fetch_animals(query)
        objects = parse_response(resp)
        animals = []
        for a in objects[:count]:
            animals.append(Animal(a['name'], a.['food']))
        return animals

class PetStore(AnimalStore):
    def fetch(count, query=None, server=None, *args, **kwargs):
        query = 'type=pet AND %s' % query
        animals = super(PetFactory, self).fetch(count, query, server, *args, **kwargs)
        pets = []
        for animal in animals:
            pets.append(magic_function(animal))
        return pets

AnimalStore and PetStore are in separate modules. AnimalStore is part of a standard Animal API and doesn't change. Basically I want to extend the Animal API by fetching a list of pets using the same mechanism used for animals, and I want to be able to take advantage of all of the other built-in functions that the Animal API already provides for its Animal and AnimalStore classes.

A: You can write the __init__() for Pet to accept an instance of Animal (or really, any ojbect with the necessary attributes -- duck typing!) as well as the individual attributes. Then you could just do fluffy_as_pet = Pet(fluffy_as_animal). Or provide a class method (e.g. Pet.from_object()) to do the same, if you don't want to overload __init__(). Even if you don't control the Animal and Pet classes, you could make your own subclasses of them that behave as you need.
However, it would be best to go a step further and simply don't write code that accepts Animal but not Pet. Then you don't have to convert it. Again, duck typing -- if an object has the right attributes, you can use it regardless of its type.

A: You could do
fluffy_as_pet = object.__new__(Pet)
fluffy_as_pet.__dict__ = fluffy_as_animal.__dict__.copy()

or
from copy import copy
fluffy_as_pet = copy(fluffy_as_animal)
fluffy_as_pet.__class__ = Pet

but both those ways are probably more of a hack than a clean solution.

A: I ended up using delegation (credit should go to S.Lott):
class Animal(object):
    def __init__(self, name=None, food=None):
        self.name = name
        self.food = food

    def eat(self):
        print "The %s eats some %s" % (self.name, self.food)

class Pet(object):
    def __init__(self, animal=None):
        self.animal = animal

    def __getattr__(self, key):
        return getattr(self.animal, key)

    def __setattr__(self, key, value):
        return setattr(self.animal, key, value)

    def eat(self):
        return self.animal.eat()

    def pet(self):
        print "You pet the %s." % self.name

    def feed(self):
        print "You put some %s into the bowl." % self.food
        self.eat()

I only hope I implemented it correctly; either way, it works!

A: Personally I would use a classmethod for this:
class Animal(object):
    def __init__(self, name):
        self.name = name

    @classmethod
    def fetch(cls, name):
        # DB code left out intentionally.
        return cls(name)

class Dog(Animal):
    def bark(self):
        print("woof")

That way calling Dog().get('fido') will return an object of type Dog and Animal().get('Mickey') will return an object of type Animal.


text:
Q: npm ERR! Invalid Version: Please I got the below error while setting up an angular project

npm WARN config global --global, --local are deprecated. Use --loca tion=global instead.
npm ERR! Invalid Version:

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Local\npm-cache_logs\2022-08-02T17_5
8_35_503Z-debug-0.log

The version in the package.json is
{
  "name": "angular-front-end",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },


text:
Q: PHP not posting information from database I'm trying to post information from a database I created but it's not working.
I keep getting this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Content Calendar' ORDER BY Program' at line 1
I've googled and everything I show says that with a table with spaces (which I was stupid for naming it that btw) is using 'Content Calendar'. Is there another error that I'm not catching? Thanks for your help.
<?php
require_once("db_connx.php");
$result = mysql_query("SELECT * FROM 'Content Calendar' ORDER BY Program") or die($myQuery."

".mysql_error());
echo "

Program
Air Date
Description
Production
Promotion
Web

";
while($row = mysql_fetch_array($result)){
  echo "
";
  echo "" . $row['Program'] . "	";
  echo "" . $row['Air Date'] . "	";
  echo "" . $row['Description'] . "	";
  echo "" . $row['Production'] . "	";
  echo "" . $row['Promotion'] . "	";
  echo "" . $row['Web'] . "	";
  echo "
";
  }
echo "
";
require_once("db_connx_close.php");
?>

A: Your table should not be wrapped in quotes but with backticks since you have two words seperated by a space.
$result = mysql_query("SELECT * FROM `Content Calendar` ORDER BY Program") or die($myQuery."

".mysql_error());

Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

A: I have 2 suggestions
1 is use backticks
$result = mysql_query("SELECT * FROM `Content Calendar` ORDER BY Program") or die($myQuery."

".mysql_error());

or 2 rename your table as Content_Calendar
$result = mysql_query("SELECT * FROM Content_Calendar ORDER BY Program") or die($myQuery."

".mysql_error());


text:
Q: Omit meta-data from oData response I'm experimenting with writing Javascript/JSONP queries against an WCF oData API. For performance reasons, I'm trying to keep the responses succinct. The default seems to be for the oData endpoint to return uri and type metadata with every returned result. This information can take up a significant portion of response payload. Is there a way to ask the oData endpoint to omit this information?

A: Currently there's no way in the OData protocol to achieve that. Technically the metadata is part of the response, that's what makes it OData and not just arbitrary JSON.


text:
Q: How to access SessionFactory from spring-dispatcher-servlet.xml to DAO I am creating a spring web application with help of hibernate. I have created spring-dipatcher-servlet.xml for all the configuration. I want to access the database using hibernate without creating the hibernate.cfg.xml file as I am using spring. I am getting Null Pointer Exception while accessing the Session Factory in DAO.
Following are the snippets of what I have done till now.
----web.xml----
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>quiz_mcq</display-name>
    <welcome-file-list>
        <welcome-file>welcome.htm</welcome-file>
    </welcome-file-list>

    <servlet>
          <servlet-name>spring-dispatcher</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>

   <servlet-mapping>
      <servlet-name>spring-dispatcher</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>

</web-app>

---spring-dispatcher-servlet---
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

     <context:component-scan base-package="com.quiz_mcq.controller" />

   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/quiz_mcq" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

    <bean id="sessionFactory"  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="packagesToScan" value="com.quiz_mcq.bean"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>

    </bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/" />
      <property name="suffix" value=".jsp" />
    </bean>

</beans>

---controller ---
@Controller
public class QuizMcqController {

    UserService userService;

    @RequestMapping(value="/welcome.htm")
    public ModelAndView redirectToLoginPage(){

        ModelAndView modelAndView = new ModelAndView("login");
        return modelAndView;

    }

    @RequestMapping(value="/AuthenticateUser.htm", method = RequestMethod.POST)
    public ModelAndView authenticateUser(@RequestParam("username") String username, @RequestParam("password")String password){

        userService = new UserService();
        boolean flag  = userService.authenticate(username,password);
        if(flag){
            ModelAndView modelAndView = new ModelAndView("login");
            return modelAndView;
        }
        else{
            ModelAndView modelAndView = new ModelAndView("wrong");
            return modelAndView;
        }

    }

}

--- Service ---
public class UserService {

    User user;
    UserDao dao;

    public boolean authenticate(String username, String password) {
        user = new User();
        user.setUsername(username);
        user.setPassword(password.toCharArray());

        if(dao.authenticateUser(user))
        {
            return true;
        }

        return false;

    }
}

---DAO ---
@Repository
public class UserDao implements IUser {

    @Autowired
    SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public boolean authenticateUser(User user) {
        String username = user.getUsername();
        char[] password = user.getPassword();
        System.out.println(username +" <----> "+password);
        String hql = "from User where username='username' and password ='password'";
        Query query = getSessionFactory().openSession().createQuery(hql);
        List list = new ArrayList();
        list = query.list();
        if (list.size() > 0 && list != null) {
            return true;
        }

        return false;
    }

}

How can I resolve my issue, what I am doing wrong?
Thanks in advance. Your help is appreciated.

A: here the problem is currently your dispatcher servlet does not know how to create and set the bean SessionFactory from. (As you see, your setSessionFactory is in UserDao class )
you may need to declare UserDao bean in spring-dispatcher-servlet.xml.
for eg:
<bean id="userDAO" class="your.package.nameforUserDao">
  <property name="sessionFactory" ref="sessionFactory" />
</bean>


text:
Q: Laravel y PHPUnit Tengo como entorno de desarrollo Windows 8 y Laragon. He creado un nuevo proyecto para empezar a aprender sobre el TDD. Cuando intento ejecutar el comando phpunit desde la consola, en la raíz del proyecto, tal como indica la documentación, me responde bash: phpunit: command not found.
Los tests que vienen por defecto se ejecutan si tecleo vendor/bin/phpunit.
Esto es normal? Por qué no me funciona el comando tal como aparece en la documentación? Puede ser un error en la creación del proyecto?


text:
Q: Pip, wheel and console_scripts I'm running into the following problem with python whl packages:
I have a package with a single entrypoint defined in my setup.py.
When I run pip install ., it installs the package AND the entry point wrapper properly.
When I run python setup.py bdist_wheel followed by pip install thing.whl, it only install the package, but not the entrypoint.
How do I install the entrypoint properly from the created wheel package?
PS: When I unzip the wheel package, I do find "entrypoints.txt" with the expected entry. It just doesn't get installed in the environment bin.

A: Wheels used to include pre-generated console script wrappers in the package, but this was sub-optimal and the files were removed. The installer is supposed to generate these wrapper scripts instead, but pip has not yet been updated to follow suit, see issue 1067.
Until pull request 1251 is part of a release, you'll have to use a separate command to install console scripts:
python -m wheel install-scripts thing.whl

See Setuptools scripts handling in the Wheel documentation.
The pull request was merged earlier this month (November 2014), and will be part of the upcoming 6.0 release. You could also use pip to upgrade itself to the development version from GitHub with:
pip install git+https://github.com/pypa/pip.git


text:
Q: Scheme to C translator I tried to generate C code starting from a scheme function and I do not manage to find any translator from scheme to C.  I tried to convert this function to C.
(define f
  (lambda(n)
     (if (= n 0) 1
         (* n (f (- n 1))))))

(display (f 10))
(newline)

I tried to use gambit (gsc) and it generates a C file that looks merely like a file to load in some interpreter, not a file containing a main function that can be executed.
Is there some application that generates C code that can be directly executed?  The functions from standard scheme library like display should be linked with some object file.
EDIT:
My purpose is to understand the algorithms used by professional translators.

A: There are many such translators, dating back at least to the 1980s I think  CHICKEN is a good current one.
If you want to use that:

*

*get CHICKEN;

*build & install it with the appropriate make incantation (this was painless for me on OSX, it should be very painless indeed on Linux therefore, although it may be harder on Windows);

*stash your code in a file I'll call f.scm.

*if you want to see the C code, compile with chicken f.scm which will produce a few hundred lines of incomprehensible C;

*if you want just the executable, use csc to create it.

There is an extensive manual which you will need to read if you want to do anything nontrivial, such as linking in C libraries or talking to Scheme code from C.

Without knowing what you are after, this smells as if it may be an XY problem.  In particular:

*

*if you want a Scheme system which will allow you talk to code written in C, then you probably want a system with an FFI, not one that compiles to C;

*if you want a Scheme system which will create native executables, then you probably want, well, a Scheme system which will create native executables, not one which compiles to C.

There are many examples of each of these.  Some of these systems may also compile to, or via, C, but one does not depend on the other.
Finally, if you want to understand how Scheme compilers which target C work (or how Scheme compilers which target any language, including assembler), then the traditional approach probably still works best: find a well-written one for which source is available, and read & tinker with its source code.

A: Basically no scheme to C translators will do what you want. They create hideous code not meant to be read and they rely on the underlying C compiler to do much of the optimization. Chicken and Gambit make use of header files while I have Stalin, which does not but it is based on R4RS instead of R5RS and later.
You are probably better off reading Abdulaziz Ghuloum's paper An Incremental Approach to Compiler Construction (PDF) or perhaps Matt Mights articles on parsing, continuations and compilations. Longer down he actually has a Scheme to C and Scheme to Java with different approaches to closure conventions. In the end nothing beats doing it yourself so have a go!


text:
Q: Match on ID in URL with RegEx I am looking to find a random alpha-numeric ID from a URL returned in some JSON.  Using the example:
"responseURL" : "http://sutureself.com/userid/123abc"

... I want to just match on the 123abc.  So far I have:
http://sutureself.com/userid/([a-z0-9]+)

... but this matches the whole URL.  What do I need to add to only match this ID?  Note, the length of the ID can differ.

A: How about this:
[^/]+(?="})

Working regex example:
http://regex101.com/r/pT3fG8

A: Looks like you need to set the template to "$1". See comments in this related post.