text:
Q: uploading files through html form using javascript calling php I have an HTML form in which I have to upload 3 files.
I have to call a create.js script after form submission which uses getElementById to format the input in desired way. Then it uses a xmlHTTPRequest to call create.php which inserts the form data into mysql database, and in the mean time fetches some data that it sends back to create.js using json_encode.
So I don't use the form action attribute but instead use the onClick attribute on my Submit button to call create.js.
But I have to upload my 3 files also on clicking Submit. I tried using $_FILE['file1']['name'] and other $_FILE[][] variables, where I use <input type="file" name="file1" id="file1"> to uplaod my first file but it gave the following error:
Undefined index: file1 in C:\xampp\htdocs\mywebsite\sites\all\themes\danland\create.php on line 77
So how can I incorporate my code for storing uploaded files on my server in the same php that returns xmlhttp.responseText to my .js file ?
I also tried putting my code of uploading in upload.php and called it using <form action="the/correct/path/upload.php"> besides using onClick = "my_create.js_function()" in my submit button but it did not work
Note that I have read  html upload using ajax and php  and know that I cannot upload my file using xmlhttprequest, but I am not trying to do that. I want my xmlhttprequest to fetch data after submit is clicked and my submit button to also store my files.
My HTML form is:

Enter Details

<form id="create_projectform1" name="create_projectform1" method="POST" enctype="multipart/form-data" action="http://localhost/mywebsite/sites/all/themes/danland/create_new_project_upload.php">

<input type="text" name="project_id" id="project_id" required/>

<input type="text" name="project_name" id="project_name" required/>

<input id="project_start_date" onClick="new datepickr('project_start_date')" required/>

<select id="project_geography" name="project_geography">
<option value="">Select Country </option>
</select>

<input type="file" name="file1" id="file1">

<input type="file" name="file2" id="file2">

<input type="file" name="file3" id="file3">

<input type="submit" class="searchinterfaceform1go" value="Search" onClick="create_new_project()"/>     <button class="searchinterfaceform1go" type="reset" value="Reset"> Reset  </button>

</form>

My create.js:
function create_new_project( )
{
    alert("entered");
    var project_id = document.getElementById("project_id").value;
    var project_name = document.getElementById("project_name").value;
    var project_start_date = document.getElementById("project_start_date").value;
// some more getElementByID
    var error_para = document.getElementById("my_first_para");
    var my_error = "";
    error_para.innerHTML =  my_error;

    // some string manipulation with the above defined variables

    project_start_date = date_fixer(project_start_date);
    project_completion_date = date_fixer(project_completion_date);

    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    var params = "project_id=" + project_id + "&project_name=" + project_name ; // + some more parameters

    var url = "http://localhost/mywebsite/sites/all/themes/danland/create.php";
    xmlhttp.open("POST",url,true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            var val = xmlhttp.responseText;
            //alert(val);
                    var jsonData = JSON.parse(val);
                    // some manipulation with json data
            var answer = document.getElementById("this_is_my_new_para");
            answer.innerHTML = jsonData;
        }
    }
    xmlhttp.send(params);
}

function date_fixer(my_date)
{
    // code here that works fine
}

My create.php:
<?php

    define('DB_SERVER', 'localhost');
    define('DB_USERNAME', 'this_user');
    define('DB_PASSWORD', 'this_password');
    define('DB_DATABASE', 'mywebsite');

    $project_id = $_POST["project_id"];
    $project_name = $_POST["project_name"];
    $project_start_date = $_POST["project_start_date"];
        // some more $_POST[]

    $date_status1 = date_fixer($project_start_date);
    $date_status2 = date_fixer($project_completion_date);
    //echo "date status 1 is $date_status1 and date_status2 is $date_status2";
    if ( $date_status1 == -1 || $date_status2 == -1 )  // not a valid date
    {
        echo "The date was not in correct format. Please use the date picker";
    }
    else
    {
        try
        {
            $db = new PDO('mysql:host=' .DB_SERVER . ';dbname=' . DB_DATABASE . ';charset=utf8', DB_USERNAME,  DB_PASSWORD);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $query_geography = "INSERT into " . DB_TABLE . "( projectID, project_name, start_date) values ( (:pid), (:pname), (:sdate))";
            $parameters1 = array(':pid'=>$project_id, ':pname'=>$project_name, ':sdate'=>$project_start_date);
            $statement1 = $db->prepare($query_geography);
            $statement1->execute($parameters1);
        }
        catch(Exception $e)
        {
            echo 'Exception -> ';
            var_dump($e->getMessage());
        }
    }

    function date_fixer($my_date)
    {
        // valid function that works fine
    }

    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file1"]["name"]);
    $extension = end($temp);
    print_r($temp);
    print_r($extension);

    if ( ( ($_FILES["file1"]["type"] == "image/gif") || ($_FILES["file1"]["type"] == "image/jpeg") || ($_FILES["file1"]["type"] == "image/jpg") || ($_FILES["file1"]["type"] == "image/pjpeg") || ($_FILES["file1"]["type"] == "image/x-png") || ($_FILES["file1"]["type"] == "image/png") ) && ($_FILES["file1"]["size"] < 20000) && in_array($extension, $allowedExts) )
    {
        if ($_FILES["file1"]["error"] > 0)
        {
            echo "Return Code: " . $_FILES["file1"]["error"] . "
";
        }
        else
        {
            echo "Upload: " . $_FILES["file1"]["name"] . "
";
            echo "Type: " . $_FILES["file1"]["type"] . "
";
            echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " kB
";
            echo "Temp file: " . $_FILES["file1"]["tmp_name"] . "
";
            if (file_exists("upload/" . $_FILES["file1"]["name"]))
            {
                echo $_FILES["file1"]["name"] . " already exists. ";
            }
            else
            {
                move_uploaded_file($_FILES["file1"]["tmp_name"], "upload/" . $_FILES["project_file1"]["name"]);
                echo "Stored in: " . "upload/" . $_FILES["project_file1"]["name"];
            }
        }
    }
    else
    {
        echo "Invalid file";
    }

?>

A: to get values from $_FILE you have to set form enctype to multipart/form-data.
if you want to read the value of file field then in jQuery simply write $('#id_filefield').val();


text:
Q: Is there a way to Change how long the Xbox record time is? I am making a Xbox gameplay of bendy and the ink machine for my YouTube channel and I need the recording time last longer than 10minutes. Is there a way to change it?

A: I think the best option on Xbox would be to use something like Mixer.  Mixer is installed by default, and has the option to record streams.  You will have to change your settings to enable a recording of the stream.
See https://windowsreport.com/save-mixer-streams-xbox/ for details on how to enable recording of your stream.

A: To record longer than 10 minutes you are going to need a USB 3 hard drive or stick. Connect it to your Xbox, then go in to settings and change video recording from internal storage to external storage. Then you will be able to record up to 1 hour and it will be saved on the hard drive or stick.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Suppose we had an algorithm that took in an array of strings, sorted each string, and then sorted the full array. What would the runtime be? The questions is:
Suppose we had an algorithm that took in an array of strings, sorted each string, and then sorted the full array. What would the runtime be?
The solution is given as below:

What i find peculiar in the above solution is this: "You should also take into account that you need to compare the strings. Each string comparison takes O (s) time.There are O (a log a) comparisons, therefore this will take O (a*s log a) time."
What do we need the comparisons for?
It would take s log s time to sort a string. Say there a strings hence the total time taken would be a*s log s
Now the problem has shrunken down to simply sorting a given array which you can do in a log a time, hence the total time taken is a*s log s + a log a = a (s log s + log a)
Where did I go wrong in my thought process?
The question is taken from the book, Cracking The Coding Interview

A: Sorting a list of numbers assumes that comparisons occur in O(1) constant time, giving the nlogn complexity, in terms of number of comparisons. However when we are sorting an enumerable whose members require a time x to compare,the run-time becomes xnlogn. This is because we are performing an action that requires x time, nlogn times.
But, I must also argue, that strings are a direct bijection to base 26. Since we consider comparison in base 10 to occur in constant time, there is no reason not to extend this to the strings which are essentially numbers in base 26. This really depends on the implementation of the string comparing mechanism. So, depending on how string comparison is done, we end up with two possible runtimes.
Yours is correct, if and only if we assume strings to be compared as numbers in base 26, and assuming that can be done in constant time.
Otherwise, sorting in general takes (Comparison time) x nlogn


text:
Q: Is there a simple way for temporary hiding the Teechart BackImage? I'm looking for a simple way (if exist) for temporary hiding (and then show it again) of Theechart BackImage.
Something like:
Chart1.Backimage.Visible := false; // then true

I know how to change the back image by code from a stream or file, such as:
Chart1.BackImage.LoadFromFile(<An image file name>);

But wonder if there is a simple way to do it.

A: Set Chart1.BackImage to nil in order to remove it.

A: No easy hide/show/visible etc. To hide the image you can set the style to custom and set the bounds / positions to not show anything. To bring it back set to what is was previously, for example tile and all 0's.
  Chart1.BackImage.Mode := pbmCustom;  // In the UI this is Style
  Chart1.BackImage.Left := 0;
  Chart1.BackImage.Right := 1;
  Chart1.BackImage.Top := 0;
  Chart1.BackImage.Bottom := 1;

To see properties and values set things manually in the IDE design time on a form and then view the form as text to see what the properties and values are.


text:
Q: Characterization: Injective morphism of sheaves Let $X$ be an arbitrary topological space and $\varphi : \mathcal{F} \to \mathcal{G}$ be a morphism of sheaves over $X$. We call $\varphi$ injective if $\mathcal{K}:=\ker(\varphi) = 0$.
I need to show that this is equivalent to the statement that for all $p \in X$ the morphisms $\varphi_p : \mathcal{F}_p \to \mathcal{G}_p$ induced on the germs are all injective.
My main problems are the following:

*

*Embarrassingly, I do not get what $\ker(\varphi) = 0$ really means. Let us say we have sheaves over rings. Then the kernel is the zero ring. But does this also mean that for any open set $U \subset X$ the sections $\mathcal{K}(U) = \ker(\varphi_U)$ is also the zero ring?

*I still have no intuition for stalks and germs. We have defined stalks as some set equipped with some weird equivalence relation and germs as their equivalence classes. Neither do I know what injectivity means for the $\varphi_p$ nor how I get the desired conclusions with these.

Could anyone explain this to me? Thanks in advance.

A: For your first question, yes, that's exactly what it means to say that the kernel sheaf is 0.  For your second question, have you studied complex analysis?  The identity theorem states that if two holomorphic functions agree on an open subset, then they are identical wherever they are both defined.  Thus it makes sense to identify holomorphic functions that agree on some open subset and only consider equivalence classes, aka germs.  This is exactly the equivalence relation defining the stalk of a sheaf.
The stalk of a sheaf is defined as the direct limit of the sheaf with its restriction maps:
$$
\mathcal{F}_p = \varinjlim_{U \ni p} \mathcal{F}(U)
$$
taken over all open sets $U \subseteq X$ containing $p$.  Given a morphism $\varphi$ of sheaves, the universal property of the direct limit yields an induced map on the stalks.  More concretely, we can choose a representative $(s,U)$ for a germ $s|_p$.  Since the morphism commutes with the restriction maps, then
\begin{align*}
\varphi_p(s|_p) &= \varphi_p(\operatorname{res}^U_p(s)) = \operatorname{res}^U_p(\varphi_U(s)) \, .
\end{align*}
(Note that the first restriction map is for the sheaf $\mathcal{F}$, $\operatorname{res}^U_p: \mathcal{F}(U) \to \mathcal{F}_p$, while the second is for the sheaf $\mathcal{G}$, $\operatorname{res}^U_p: \mathcal{G}(U) \to \mathcal{G}_p$.)
So to compute the action of the stalk map $\varphi_p$ on a germ, we just compute the action of the morphism on a representative for the germ, and then restrict to the stalk.
EDIT: Here's a solution to the problem:
Assume $\varphi_p$ is injective for all $p$.  Suppose $U$ is an open set and $s \in \ker(\varphi_U)$, so $\varphi_U(s) = 0$.  Given $p \in U$, then
$$
\varphi_p(s|_p) = \varphi_p(\text{res}^U_p(s)) = \text{res}^U_p(\varphi_U(s)) = \text{res}^U_p(0) = 0 \, .
$$
Since $\varphi_p$ is injective, then $s|_p = 0$, so there exists an open set $V_p \subseteq U$ with $p \in V_p$ such that $\text{res}^U_{V_p}(s) = 0$.  Note that the collection $\{V_p\}_{p \in U}$ forms an open cover of $U$.  Since $\mathcal{F}$ is a sheaf and $\text{res}^U_{V_p}(s) = 0$ for all $p \in U$, then $s = 0$ by local determination (the first sheaf axiom).  Thus $\ker(\varphi)(U) = \ker(\varphi_U) = 0$ for all $U$.
Conversely, assume $\ker(\varphi_U) = 0$ for all $U$.  Given $s|_p \in \ker(\varphi_p)$, choose a representative $(s,U)$ for $s|_p$.  Then
$$
0 = \varphi_p(s|_p) = \varphi_p(\text{res}^U_p(s)) = \text{res}^U_p(\varphi_U(s)) \, .
$$
Then there exists an open set $V \subseteq U$ containing $p$ such that
\begin{align*}
0 = \operatorname{res}^U_V(\varphi_U(s)) = \varphi_V(\operatorname{res}^U_V(s)) \, .
\end{align*}
Since $\varphi_V$ is injective, then $\operatorname{res}^U_V(s) = 0$, so
$$
s|_p = \operatorname{res}^U_p(s) = \operatorname{res}^V_p(\operatorname{res}^U_V(s)) = \operatorname{res}^V_p(0) = 0 \, .
$$


text:
Q: How do I correctly implement a basic first person camera in OpenGL? I am new to OpenGL and was trying to create a simple maze that i can traverse through using a first person perspective. I have the maze rendering and all that just fine. But my first person camera perspective ends up being more of a third person camera. The camera revolves around a certain point infront of the camera.
My Code for actual rotation and translation
void camera(){
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotatef(pitch, 1, 0, 0);
    glRotatef(yaw, 0, 1, 0);
    glTranslatef(player.x, player.y, player.z);
}

This is also the first translations and rotations that happen in rendering.
Thanks for any help.

A: The camera transformation needs to be inverted, so that you are moving the camera position, in this case the position of the player, to the origin:
glTranslatef(-player.x, -player.y, -player.z);

A: I suggest that you build your maze, leave it alone, and then use gluLookAt() to have your first-person perspective.  What you're doing now is standing still and moving the maze around you. You're doing it the hard way.


text:
Q: How is this logarithm problem solved? If $\dfrac{xy\log xy}{x+y} = \dfrac{yz\log yz}{y+z} = \dfrac{zx\log zx}{z+x}$ show that $x^x = y^y = z^z$.
I tried equating to a constant $k$ and adding up
I also tried adding up the numerators and denominators
to find each ratio
But still i am not able to figure out how to reach the final result

A: Rewrite
$$\frac{\log(x)+\log(y)}{\frac1x+\frac1y}=
\frac{\log(y)+\log(z)}{\frac1y+\frac1z}=
\frac{\log(z)+\log(x)}{\frac1z+\frac1x}.$$
Then by the rules of proportions,
$$\frac{\log(x)}{\frac1x}=\frac{\log(y)}{\frac1y}=\frac{\log(z)}{\frac1z}.$$


text:
Q: begin{align} behaving oddly - Lines after (10) show up as exponents I'll let the picture speak for itself.

It's probably a silly mistake but I have been awake for the past 20 or so hours and in my current state I can't, for the life of me, find the mistake that causes this.
Any pointers for a dumbfounded Greek?

A: No, not the lines are as exponents, but numbers of lines are below. It is because lines are too long to leave space for two-cipher numbers. They are as long, as the longest one. Your usage of align is, well, nonstandard. An ordinary usage is
(first part) & (second part) \\

Hence dividing 9th line in a manner
&(implication)\\
& \qquad (the Greek text)\\

should solve the problem. The rest of lines shold be of the form
& (text of line) \\

if you are accepting aligning to the left, of course.


text:
Q: Performance: Android Webview vs Views Datasource + parsing JSON If a developer is only looking to display specific Views blocks, rather than full webpages, would it seem worthwhile to rebuild the content as XML directly from the output of a Views datasource? Webview seems easier to implement, but I have a feeling it would lead to extra load times and overhead.
Please enlighten me!

A: From your answer it is not possible to understand the complexity of your web page that you wish to display, but beware that the usage of WebView may lead to a lot of compatibility issues.
If your webpage is easy to implement natively - I'd recommend going native way. From the performance standpoint it would be the best solution anyway.
If your webpage is complex, check out the Crosswalk project. It's XWalkView is much more reliable than WebView. Beware, that the downsides of this way would be:

*

*Bigger apk size, from my experience not less than +=20Mb

*RAM overhead

*Extra time on XWalkView instantiation


text:
Q: Dificuldade em realizar CRUD de dados com FullCalendar e Django/Python Estou tentando utilizar o FullCalendar no meu projeto Django e estou com dificuldades em fazer o CRUD dos dados.
Eu gostaria que tudo funcionasse na mesma tela,ou seja, quando o usuário seleciona datas no calendário, o modal aparece para inserir os valor (título e datas), quando clica em um evento, aparece o modal para editar o evento e um botão para removê-lo.
Até agora o que eu consegui fazer foi o seguinte:


text:
Q: does WPF binding bypass the codebehind setter for dependencyproperties? I may be doing this all wrong... so hang with me
I am making a user control with a property which the user can bind to.  The in setter for the property, I bind the PropertyChanged listener to the property so I can react to changes to its state.  The code behind for this user control looks like this:
        public static readonly DependencyProperty NodeProperty =
        DependencyProperty.Register("Node", typeof(MockRequirementWrapper), typeof(RecNode2));
    public MockRequirementWrapper Node
    {
        get
        {
            return (MockRequirementWrapper)GetValue(NodeProperty);
        }
        set
        {
            if(Node != null)
                Node.PropertyChanged -= Update;
            SetValue(NodeProperty, value);
            Node.PropertyChanged += new PropertyChangedEventHandler(Update);
            OnPropertyChanged(this, "Node");
        }
    }

then, in another user control, I bind to this property a node I've created elsewhere like this:
<local:RecNode2 Node="{Binding}"/>

What I am finding is the recnode exists and is bound to a node... but if I put a breakpoint in the setter, it never gets called.  Am I misunderstanding how the binding works?  How do I add my listener when the node changes?

A: The framework will always call GetValue and SetValue directly, the property is just for convenience and sould never contain logic besides those calls.
If you want to do something on changes register a PropertyChangedCallback in the Metadata when registering the DependencyProperty.
Taken from http://msdn.microsoft.com/en-us/library/ms753358.aspx:
public static readonly DependencyProperty AquariumGraphicProperty = DependencyProperty.Register(
  "AquariumGraphic",
  typeof(Uri),
  typeof(AquariumObject),
  new FrameworkPropertyMetadata(null,
      FrameworkPropertyMetadataOptions.AffectsRender,
      new PropertyChangedCallback(OnUriChanged)
  )
);
public Uri AquariumGraphic
{
  get { return (Uri)GetValue(AquariumGraphicProperty); }
  set { SetValue(AquariumGraphicProperty, value); }
}


text:
Q: How can I trigger runs for actual Emails which arived before enabling Logic App? I have a Logical App which uses the when a new email arrives (V3) - trigger

the problem is that e-mails which are new and unread will not proccessed by the  LogicApp if they arrived before I enabled the Logic App.
What could I do to trigger or retrigger  runs for this emails.
or is that the problem the webhook trigger when a new email arrives (V3) nad I should use the polling Trigger (V2).
So all advices  for retriggering on V3-trigger or change app to v2 or other proposals are very welcome.

A: According to some test and summarize from the comments, it seems we didn't understand the "when a new email arrives (V3)" trigger correctly. I do some more test for the trigger and find the feature with two situations:
1. If we create the trigger(or create the Office365 connection) first but disable the logic app, then receive an email, then enable the logic app. It can be triggered by the received email.
2. If receive the email first, then create the trigger(or create new Office365 connection in logic app). The logic app can't be triggered by the received email.
In a word, only the emails received after the creation time of Office365 connection, the logic app can be triggered.
===============================Update================================
If you think it is not guaranteed, you can do it by "Get emails" action to get all of the unread emails.


text:
Q: Is MAPI supported with Outlook 2010 I am trying to use MAPI to display a public calendar in SharePoint. The below sample code works perfectly with a machine having Outlook 2007 installed. But Outlook 2010 does not displays a big white block.
Is this security? Is MAPI supported in Outlook 2010? Any advise is greatly appreciated.
<OBJECT classid=CLSID:0006F063-0000-0000-C000-000000000046
id=ViewCtlFolder
width="100%"
height="430"
codebase="http://activex.microsoft.com/activex/controls/office/outlctl x.CAB#ver=9,0,0,3203">
<param name="Namespace" value="MAPI">
<param name="Folder" value="\\Public Folders\All Public Folders\Training Calendar">
<param name="Restriction" value="">
<param name="DeferUpdate" value="0">
</OBJECT>

A: Outlook 2010 supports MAPI just fine. Unfortunately, you are not using MAPI. You are using the Outlook View Control.
Support for this control is still included in Outlook 2010, but it's use is restricted to in-process Outlook use, like custom folder pages.
Quote from the first link:

Do not use the View Control in any scenario outside the Outlook process, such as in an HTML page hosted in a browser. Out-of-process scenarios are not supported.


text:
Q: Recover disk space used by Windows installer Updating to Windows 8 Pro on my PC consumed an additional 20 Gb or so and I'd like them back. How do I recover the space used by the installer / updater?

A: Use Disk Cleanup with the Clean up system files option.

A: You should find a Windows.old folder in your C drive
Copy any stuff you need and delete it


text:
Q: Is it possible to create loop which create instance of classes? I want to create console app which read userinput value and create multiple instances of one class and then run void say() in all class instances.
Code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int botsnumber = 0;
            Console.WriteLine("Type number: ");
            botsnumber = Int32.Parse(Console.ReadLine());
            for (int i = 0; i < botsnumber; i++)
            {
                //Here generate bots: Bot b1 = new Bot(); Bot b2 = new Bot();
               // Bot b = new Bot();
            }
            b.say();// b1.say(); b2.say(); b3.say(); ...
        }
    }

    class Bot
    {
        public static void say()
        {
            Console.WriteLine("Hello!");
        }
    }
}

A: Put the instances into a list, fill it, after that, loop the list and call say
botsnumber = Int32.Parse(Console.ReadLine());
var list = new List<Bot>();
for (int i = 0; i < botsnumber; i++)
{
   Bot b = new Bot();
   list.Add(b);
}
list.ForEach(b => b.say());

And you don't need to put static in your method say
class Bot
{
    public void say()
    {
        Console.WriteLine("Hello!");
    }
}

A: Like this i guess
public static List<Bot> bots = new List<Bot>();

...

for (int i = 0; i < botsnumber; i++)
{
    bots.Add(new Bot);
}

...

bots[0].Say();
bots[1].Say();

A: I think you want to call say() inside the loop, and make it a non-static method:
for (int i = 0; i < botsnumber; i++)
{
     Bot b = new Bot();
     b.Say();
}

class Bot
{
    public void Say()
    {
        Console.WriteLine("Hello!");
    }
}

Although note that in many ways there's no point in creating a stateless object instance that you immediately discard, so ... in real usage I would either expect some state, or I'd expect it to be a static method.
Alternatively, you could create all the bots first, accumulate them in a list, then loop over that - again, whether this is sensible depends on context, but:
var bots = new List<Bot>(botsnumber);
for (int i = 0; i < botsnumber; i++)
{
     bots.Add(new Bot());
}
// ...
foreach(var bot in bots)
{
    bot.Say();
}

A: You could either immediately call say, or call them all after creating all the bots
for (int i = 0; i < botsnumber; i++)
{
    //Here generate bots: Bot b1 = new Bot(); Bot b2 = new Bot();
    Bot b = new Bot();
    b.say();
}

// or

var bots = new List<Bot>();
for (int i = 0; i < botsnumber; i++)
{
    //Here generate bots: Bot b1 = new Bot(); Bot b2 = new Bot();
    bots.Add(new Bot());
}
foreach (var bot in bots)
{
    bot.say();
}


text:
Q: Updating MySQL 5.6 query to MySQL 5.7 The below same query is returning different results for MySQL 5.6 and MySQL 5.7
SELECT T1.ID, T1.NAME
FROM T1
JOIN T2 ON T1.ID = T2.S_ID
JOIN T3 ON T2.R_ID = T3.DR_ID
WHERE
T2.START_DATE <= '2022-10-01'
T2.END_DATE > '2023-10-01'
AND T3.DT_ID = 2
ORDER BY T1.ID

I expect the above query to return same results in MySQL 5.6 and MySQL 5.7 databases which have the same data.
Unfortunately, MySQL 5.7 is returning more records which is wrong, but if I remove ORDER BY T1.ID for MySQL 5.7 it has the same results as what I get using MySQL 5.6 (with ORDER BY) and the result is correct.


text:
Q: Save features from hidden layers from an auto-encoder model using keras in runtime I am training an auto-encoder model and  want to save the features of each image during runtime from encoder part and use it later for feature matching.
My model structure is-
train_data_dir = '/train'
test_data_dir = '/test'
nb_train_samples = 100
nb_validation_samples = 25
nb_epoch = 2
batch_size = 5
input_img = Input(shape=( img_width, img_height,3))

x = Conv2D(128, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)

x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(32, (3, 3), activation='relu',padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(128, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

def fixed_generator(generator):
    for batch in generator:
        yield (batch, batch)

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)
# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode=None)
#print(type(train_generator))
test_generator = test_datagen.flow_from_directory(
        test_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode=None)

autoencoder.fit_generator(
        fixed_generator(train_generator),
        epochs=nb_epoch,
        samples_per_epoch=nb_train_samples,
        validation_data=fixed_generator(test_generator),
        validation_steps=nb_validation_samples
        )

How can i save the features from encoder part during model fit. Is there any way, please suggest

A: To save the features from a autoencoder model, first you need to load the model and extract the last encoder layer from the model.
Here is the code to extract the layers of an encoder and save the features for an image:
autoencoder= load_model('model_weights.h5')
encoder = Model(autoencoder.input, autoencoder.layers[-1].output)

# Read your input image for which you need to extract features

img = cv2.imread(img)
newimg = cv2.resize(img,(512,512))
encoded_imgs = encoder.predict(newimg[None])[0]

# Save your features as an numpy array

np.save('features.npy', encoded_imgs)

After saving your feature for an input image you need to find the euclidean distance for feature matching.
file = 'sample.npy'
file = np.load(file)
file1 = "features.npy"
file1 = np.load(file1)
distance = np.linalg.norm(file-file1)
print(distance)

This code will extract the features from an image and calculate the distance between two numpy arrays.

A: Keras Functional API is the keyword, there is even a very insightful blog post on autoencoders.
Here are the key points of the example taken from the blog post:
input_img = Input(shape=(784,))
encoded = Dense(encoding_dim, activation='relu')(input_img)
decoded = Dense(784, activation='sigmoid')(encoded)
# this model maps an input to its reconstruction
autoencoder = Model(input_img, decoded)
# this model maps an input to its encoded representation
encoder = Model(input_img, encoded)

Now you can put the autoencoder.fit(...,epochs=1) method into a for-loop and look at the encoded representation with encoder.predict(your_data) to save the features.

A: In a similar task with text data, I am extracting the encoder from a trained model and saving it out. I load the encoder and do encoder.predict(input_sample) to generate encoded vector (for retrieval purpose). However every time I load and predict the output varies (keeping the same input). Is this behavior normal?

A: I think you should use
encoder = Model(input_img , encoded)

instead of
encoder = Model(autoencoder.input, autoencoder.layers[-1].output)

because autoencoder.layers[-1].output means the decoder layer which is the reconstructed original image


text:
Q: Javascript: Call object function from within a function object my problem seems to be that my object function is not visible if i call it from within an object of functions. Example Code:
function foo()
{
   this.bar = function()
              {
                 alert("hit me!");
              }

   this.sna = {
                 fu:   function ()
                       {
                          this.bar();
                       }
              };

}

this seems to refer to sna instead of foo. How do i adress foo? this.parent does not work.

A: One option is to add a reference to this:
function foo() {

  var _t = this;

  this.bar = function() { };

  this.child = {
    this.foo = function() {
      _t.bar():
    };
  };

}

A: Use a variable to refer to this(Foo). See this - JavaScript | MDN

function Foo() {
    this.bar = function() {
        console.log("hit me!");
    };

    var that = this;

    this.sna = {
        fu: function() {
            that.bar();
        }
    };

}

var foo = new Foo();
foo.bar();
foo.sna.fu();


text:
Q: Using index with lower function in postgresql To create my table and index I use the following code:
CREATE TABLE IF NOT EXISTS users (
    id SERIAL NOT NULL,
    name VARCHAR(512) NOT NULL,
    PRIMARY KEY (id));

CREATE INDEX users_name_idx ON users (lower(name::varchar(16)));

My question - is users_name_idx index used in the following queries:

*

*SELECT * FROM users WHERE LOWER(name) LIKE 'somename%'?

*SELECT * FROM users ORDER BY name?

A: Your index can be used by none of your queries, because the expression is not the same as in the queries:
test=> \d users
                             Table "laurenz.users"
 Column |          Type          | Nullable |              Default
--------+------------------------+----------+-----------------------------------
 id     | integer                | not null | nextval('users_id_seq'::regclass)
 name   | character varying(512) | not null |
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)
    "users_name_idx" btree (lower(name::character varying(16)::text))

test=> SET enable_seqscan = off;

test=> EXPLAIN SELECT * FROM users WHERE LOWER(name) LIKE 'somename%';
                                QUERY PLAN
---------------------------------------------------------------------------
 Seq Scan on users  (cost=10000000000.00..10000000012.10 rows=1 width=520)
   Filter: (lower((name)::text) ~~ 'somename%'::text)
(2 rows)

test=> EXPLAIN SELECT * FROM users ORDER BY name;
                                    QUERY PLAN
-----------------------------------------------------------------------------------
 Sort  (cost=10000000016.39..10000000016.74 rows=140 width=520)
   Sort Key: name
   ->  Seq Scan on users  (cost=10000000000.00..10000000011.40 rows=140 width=520)
(3 rows)

For the index to be used, you would have to use the same expression, including the type cast, in your queries.
In addition to that, unless your column has collation C, your index cannot be userd in LIKE queries. You'd gave to use the text_pattern_ops operator class.
I guess that the reason behind creating such an index is to reduce the size of the index, which is a commendable thing to do.
I would recommend an index like this:
CREATE INDEX ON users (lower(name::varchar(16)) text_pattern_ops);

Then use this query:
SELECT * FROM users
WHERE lower(name) LIKE 'somename%'
  AND lower(name::varchar(16)) LIKE substr('somename%', 1, 16);

The second condition could be lossy if somename is longer than 15 characters, but it can use the index. The first condition filters out the false positives.
Unfortunately, there is no trick like this when it comes to ordering.


text:
Q: Rbenv not rehashing correctly and making shims The bottom line is, rbenv isn't making shims. I've exhausted ideas of what could be the problem. After a few days of banging my head against a wall to fix but no avail, I think it's time to ask for help.
I'm attempting to make the switch from RVM to rbenv, so that could obviously be a factor here. Any ideas/help would be great.
Here's what happens:
[09:38] ~ $ gem install pry
Fetching: pry-0.10.2.gem (100%)
Successfully installed pry-0.10.2
1 gem installed

[09:39] ~ $ rbenv rehash

[09:40] ~ $ pry
bash: pry: command not found

[09:40] ~ $ rbenv which pry
rbenv: pry: command not found

[09:40] ~ $ which pry
which: no pry in (/home/caveman/.rbenv/plugins/ruby-build/bin:/home/caveman/.rbenv/shims:/home/caveman/.rbenv/bin:/home/caveman/.rbenv/shims:/home/caveman/.rbenv/bin:/home/caveman/.rbenv/plugins/ruby-build/bin:/home/caveman/.rbenv/shims:/home/caveman/.rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/lib/jvm/default/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl)

[09:41] ~ $ ~/.gem/ruby/2.2.0/bin/pry
[1] pry(main)> puts "I'm working now"
I'm working now

[09:43] ~ $ gem list | grep pry
pry (0.10.2)

Here's my gem environment:
[09:44] ~ $ gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 2.4.8
  - RUBY VERSION: 2.2.0 (2014-12-25 patchlevel 0) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/caveman/.gem/ruby/2.2.0
  - RUBY EXECUTABLE: /home/caveman/.rbenv/versions/2.2.0/bin/ruby
  - EXECUTABLE DIRECTORY: /home/caveman/.gem/ruby/2.2.0/bin
  - SPEC CACHE DIRECTORY: /home/caveman/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY:  /home/caveman/.rbenv/versions/2.2.0/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/caveman/.gem/ruby/2.2.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "--no-document"
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /home/caveman/.rbenv/versions/2.2.0/bin
     - /usr/lib/rbenv/libexec
     - /home/caveman/.rbenv/plugins/ruby-build/bin
     - /home/caveman/.rbenv/shims
     - /home/caveman/.rbenv/bin
     - /home/caveman/.rbenv/shims
     - /home/caveman/.rbenv/bin
     - /home/caveman/.rbenv/plugins/ruby-build/bin
     - /home/caveman/.rbenv/shims
     - /home/caveman/.rbenv/bin
     - /usr/local/sbin
     - /usr/local/bin
     - /usr/bin
     - /usr/lib/jvm/default/bin
     - /usr/bin/site_perl
     - /usr/bin/vendor_perl
     - /usr/bin/core_perl

Here is my .bashrc file:
[09:46] ~ $ cat .bashrc
# If not running interactively, don't do anything
[[ $- != *i* ]] && return

# If I don't set this, gem reverts back to nonexistent RVM directory.
export GEM_HOME=$(ruby -e 'print Gem.user_dir')
export GEM_PATH=$(ruby -e 'print Gem.user_dir')

export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"

And here is .bash_profile:
[09:52] ~ $ cat .bash_profile

[[ -f ~/.bashrc ]] && . ~/.bashrc

source ~/.profile

export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

A: I suspect your .bashrc is the problem. It shouldn't contain:
# If I don't set this, gem reverts back to nonexistent RVM directory.
export GEM_HOME=$(ruby -e 'print Gem.user_dir')
export GEM_PATH=$(ruby -e 'print Gem.user_dir')

export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"

Of my ~/.bashrc, ~/.profile and ~/.bash_profile files, only the last has configuration for rbenv:
# echo Using rbenv...
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

That was created when I installed rbenv, which matches the settings for my other systems where I use rbenv, including some that previously had RVM installed.
Your double PATH assignments look like the culprit. Compare the PATH for my system to yours, which is listed by gem env:
 - /Users/ttm/.rbenv/versions/2.2.3/bin
 - /Users/ttm/.rbenv/libexec
 - /Users/ttm/.rbenv/plugins/ruby-build/bin
 - /Users/ttm/.rbenv/plugins/rbenv-whatis/bin
 - /Users/ttm/.rbenv/plugins/rbenv-vars/bin
 - /Users/ttm/.rbenv/plugins/rbenv-use/bin
 - /Users/ttm/.rbenv/plugins/rbenv-update/bin
 - /Users/ttm/.rbenv/plugins/rbenv-update-rubies/bin
 - /Users/ttm/.rbenv/plugins/rbenv-gemset/bin
 - /Users/ttm/.rbenv/plugins/rbenv-env/bin
 - /Users/ttm/.rbenv/plugins/rbenv-each/bin
 - /Users/ttm/.rbenv/shims
 - /Users/ttm/.rbenv/bin

Similarly, my which pry returns:
/Users/ttm/.rbenv/shims/pry

Using rbenv's env plugin shows:
RBENV_VERSION=2.2.3
RBENV_GEMSET_ALREADY=yes
RBENV_ROOT=/Users/ttm/.rbenv
RBENV_HOOK_PATH=:/Users/ttm/.rbenv/rbenv.d:/usr/local/etc/rbenv.d:/etc/rbenv.d:/usr/lib/rbenv/hooks:/Users/ttm/.rbenv/plugins/rbenv-default-gems/etc/rbenv.d:/Users/ttm/.rbenv/plugins/rbenv-gemset/etc/rbenv.d:/Users/ttm/.rbenv/plugins/rbenv-readline/etc/rbenv.d:/Users/ttm/.rbenv/plugins/rbenv-vars/etc/rbenv.d
PATH=/Users/ttm/.rbenv/versions/2.2.3/bin:/Users/ttm/.rbenv/libexec:/Users/ttm/.rbenv/plugins/ruby-build/bin:/Users/ttm/.rbenv/plugins/rbenv-whatis/bin:/Users/ttm/.rbenv/plugins/rbenv-vars/bin:/Users/ttm/.rbenv/plugins/rbenv-use/bin:/Users/ttm/.rbenv/plugins/rbenv-update/bin:/Users/ttm/.rbenv/plugins/rbenv-update-rubies/bin:/Users/ttm/.rbenv/plugins/rbenv-gemset/bin:/Users/ttm/.rbenv/plugins/rbenv-env/bin:/Users/ttm/.rbenv/plugins/rbenv-each/bin:/Users/ttm/.rbenv/shims:/Users/ttm/.rbenv/bin:/Users/ttm/.pyenv/shims:/Users/ttm/.pyenv/bin:/Users/ttm/perl5/perlbrew/bin:/Users/ttm/perl5/perlbrew/perls/perl-5.18.1/bin:/Users/ttm/bin:/usr/local/mysql-5.6.16-osx10.7-x86_64/bin:/Users/ttm/libsmi/bin:/usr/local/git/bin:/usr/local/bin:/Library/PostgreSQL/9.2/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin
RBENV_SHELL=bash
RBENV_DIR=/Users/ttm
RUBYLIB=/Users/ttm/.rbenv/rbenv.d/exec/gem-rehash:

I'd do these steps:

*

*Modify ~/.bashrc, and the others, removing any lines referring to rbenv and/or RVM. RVM uses all three init files, plus .zshrc, whereas rbenv only seems to touch ~/.bash_profile.

*Close the terminal session. Reopen it.

*Confirm the PATH is free from all references to RVM and rbenv.

*Reinstall rbenv following the Installation instructions. It won't override the current installation, but instead will reinstall its changes to ~/.bash_profile.

*Close the terminal session again and reopen it.

rbenv should now be initialized correctly.


text: Q: Making room for TrueCrypt in front of Boot Camp Windows partition Windows on Boot Camp can run from an encrypted disk, such as TrueCrypt.  However, TrueCrypt needs a very small space (less than a MB) in front of the Windows (Boot Camp) partition to install.  How can I create this space?


text:
Q: How does SHA256 protect against active MITM attacks? I am planning to take an SSL certificate implementing SHA256. How does SHA256 protect against active Man-in-the-middle attacks?
Also, what does 256 mean in SHA256, when a certifying authority say 2048 bit encryption.

A: sha256 is a SHA-2 hash with a 256 bit output. It is currently considered a pretty secure hash.
A secure hash makes sure that a certificate can't easily be faked. A hash needs to be collision resistant. SHA-1 isn't really great anymore for this purpose (much like md5), because it has gotten too easy to create two certificates A and A' that hash to the same key. This allows an attacker to create a certificate for hisdomain.com, have it signed, and then transfer the signature to a fake certificate for, say, google.com. This presentation by Marc Stevens clarifies this method of attack.
In that sense SHA-2 protects against some forms of active MITM attack. However, there are many other factors in play: a hash is only a building block. Safe encryption algorithms and a proper algorithm are also needed.
The 2048 bit encryption refers to the key length used for the (probably) RSA key. This is the key that's actually used in the TLS communications.
See this article on the Mozilla wiki for recommendations on how to set up your servers securely.

A: The SHA256 hash, which is a hash that outputs 256 bits of very random-looking, collision-resistant information, is used to hash the document or some combination of items including the document.  Then the 2048-bit RSA key is used to "encrypt" the hash.
The value of the hash in this respect is not crypto-related at all.  It is simply the matter than a large document or other data can be hashed very quickly, and even a tiny change in the source data will yield a completely different hash.  The RSA algorithm, which is very slow and is happy for something so small as a hash output to work with, is then used to "encrypt" the hash.
I put "encrypt" in quotes here because a digital signature is the same public / private keypair regime that public key crypto uses.  Except with digital signing, the signer keeps the "encrypt" key and gives everyone else the "decrypt" key, where with public key encyption only one person has the decrypt key and many have the encrypt key.

A: The biggest weakness of asymmetric key systems is MITM. I implemented defenses against MITM attacks using SHA-2, asymmetric keys, SHA-2 authentication servers, and unique serial (PUF) on each terminal.
In fact, this may be an internationally unpublished newspaper. If you read this article and notice it, I will give you a chance first.
I am a bit bragged, but I think this is an innovative way to solve most problems in cryptography. If you have any other comments, I would like to hear them first. If you have already answered the answer, I will answer it and give you an answer when you are sure that nobody knows in a few days. Before I make the answer, someone might have another new way. If there is another way, I would like to give him a chance to answer first.
I really think this is a breakthrough in modern cryptography. If my opinion is wrong, please point out a lot of people. I want to listen modestly.
A typical conventional MITM defense is too out of date. This method is strange. There is no big difference between sending symmetric keys to prevent MITM.
https://www.youtube.com/watch?v=PPt7yvBtGRI


text:
Q: Discord.js v12 giveaway command so basically I have this giveaway command which works good but if u react with the emoji after the time u set is done it will just send "Not enough people reacted for me to draw a winner it won't pick the winner" Idk why this is happening.
client.on('message', async message =>{
  if(message.content.toLowerCase().startsWith(prefix + 'giveaway')) {
    if(!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send('You cant use this command sice youre missing `manage_messages` perm')
    let args = message.content.substring(prefix.length).split(" ")
    let time = args[1]
    if(!time) return message.channel.send('You did not specify your time');
    if(
      !args[1].endsWith("d") &&
      !args[1].endsWith("h") &&
      !args[1].endsWith("m") &&
      !args[1].endsWith("s")
    )
    return message.channel.send("You need to use d (days), h (hours), m (minutes), or s (seconds)")

    let gchannel = message.mentions.channels.first();
    if(!gchannel) return message.channel.send("I cant find that channel in the server.")
    let prize = args.slice(3).join(" ")
    if(!prize) return message.channel.send('What is the prize?')

    message.delete()
    gchannel.send(`:tada: **New Giveaway** :tada:`)
    const newEmbed = new Discord.MessageEmbed()
    .setTitle('New Giveaway')
    .setColor("RANDOM")
    .setDescription(`React with :tada: to enter the giveaway.
\nHosted By: **${message.author}** \nTime: **${time}**\nPrize: **${prize}**`)
    .setFooter(`Will end in ${time}`)
    let reaction = await gchannel.send(newEmbed)
    reaction.react("")
    setTimeout(() => {
      if ((m) => m.reaction.cache.get("").count <= 0) {
        return message.channel.send("Not enough people reacted for me to draw a winner")
      }
      let winner = (m) => m.reaction.cache.get("").users.cache.filter((u) => !u.bot).random();
      gchannel.send(`Congratulations ${winner} You just won the **${prize}**!`
      );
    }, ms(args[1]));
  }
})

A: You can't use an arrow function for no reason on your if statement, as m has not been set to anything, you will get undefined.
To fix this, you need to use the message you send as your Message object, as when you use .send() a promise is returned, which contains a Message object. This object then has the property reactions which can be used to get the reactions on the message.
For example:
if (reaction.reactions.cache.get("").count <= 0) {
    return message.channel.send("Not enough people reacted for me to draw a winner")
}

However, I would suggest using a ReactionCollector instead as you can setup a filter and a time and then an event will be fired off instead, which you can listen to and get the size of etc.
const filter = (reaction, user) => {
    return reaction.emoji.name === '';
};

const collector = reaction.createReactionCollector(filter, { time: 15000 });
// time is in ms (so 15000ms is 15 seconds)

collector.on('collect', (reaction, user) => {
    console.log(`Collected  from ${user.tag}`);
});

collector.on('end', collected => {
    console.log(`Collected ${collected.size} items`);
    // collected.size will only contain the number of  on the message, as the collector had a filter applied to it
});


text:
Q: How to migrate PostGIS spatial data to MsSql spatial data? am trying to migrate PostGIS geometry to SQL server Spatial data. which ETL i have to use. it's the first time i'll work with SQL server Spatial.
is there any Data ETL model that do this migration. thanks for help

A: You can try

*

*pgsql2shp (shapefile intermediate) and then use the sqlspatialtools to load

*OGR2OGR supports reading and writing at both ends of that pipe

*part of me wants to suggest that a PG_DUMP to text would provide SQL that could then be consumed in SQL server.

Details click here

A: try to use program brigantine to migrate PostGIS geometry to SQL server Spatial data

A: From
http://www.postgresonline.com/journal/index.php?/archives/31-GDALOGR2OGR-for-Data-Loading.html

Microsoft SQL Server (and other ODBC) to PostgreSQL
OGR has a driver that supports ODBC DSN connections. Unfortunately this will only work on Windows. Below is an example that imports all tables from a SQL Server database to PostgreSQL. In this example, the DSN I have is using NT Authentication or has the name and password encoded in the System DSN. For this you need to setup a DSN connection to the SQL Server database in ODBC Manager (we described setting up a DSN in Using MS Access with PostgreSQL, except the ODBC driver seems to only work with System DSNs not File DSNs. For more details on referencing the ODBC DSN - check http://www.gdal.org/ogr/drv_odbc.html
ogr2ogr -f "PostgreSQL" PG:"host=pghost user=pgloginname dbname=pgdbname password=pgpassword"
"ODBC:system_dsn_goes_here" -update -lco OVERWRITE=yes -nlt NONE

As noted, geometry fields seem to be created and right field types are not necessarily created. SQL Server text come in as VARCHARS and VARCHARS come in as CHARS etc. One way to get around this is to create your table structures before hand and use OGR2OGR to just load the data.
E.g.
--This will append to a table called orders reading from the SQL Server (ODBC) table orders and customers.  It will only append like-named fields.
psql -h pghost -p 5432 -U pguser -d pgdbname -c "TRUNCATE TABLE orders;TRUNCATE TABLE customers;"

ogr2ogr -append -f "PostgreSQL" PG:"host=pghost user=pgloginname dbname=pgdbname password=pgpassword port=5432"
"ODBC:system_dsn_goes_here" orders customers

Or correct the structures afterword by dropping unnecessary fields using a script generation technique similar to what we described in DML to Generate DDL and DCL. So your script builder SQL to drop all the ogc_fid and wkb_geometry fields created by OGR2OGR would look something like this.
SELECT 'ALTER TABLE ' || t.table_schema || '.' || t.table_name || ' DROP COLUMN ogc_fid;'
    FROM information_schema.tables t
        INNER JOIN information_schema.columns c
        ON (t.table_name = c.table_name AND t.table_schema = c.table_schema AND c.column_name = 'ogc_fid')
    UNION
    SELECT 'ALTER TABLE ' || t.table_schema || '.' || t.table_name || ' DROP COLUMN wkb_geometry;'
    FROM information_schema.tables t
    INNER JOIN information_schema.columns c
    ON (t.table_name = c.table_name AND t.table_schema = c.table_schema AND c.column_name = 'wkb_geometry';


text:
Q: Search filesystem for filepath using VBA I am looking for a way to search a specific folder for a subfolder containing a certain string. Below I have listed a function I typed off the top of my head to see if it would work. Well, it does work but when I am talking about searching through 6,000 folders on a network drive it just isn't fast enough.
I'm sure that there is a better way to do it but I can't seem to dig anything up on Google.

*

*Is there an object that allows me to leverage the windows built in file system searching and indexing capabilities?

*As an alternative, does someone have a way to optimize my code? The main bottleneck is the usage of instr.
Here is the code:
Function findPath(strId As String) As String
checkObj
Dim strBase As String
strBase = opt.photoBasePath

Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")

Dim baseFolder As Object
Set baseFolder = fs.getfolder(strBase)

Dim folder As Object

For Each folder In baseFolder.subfolders
    If InStr(1, folder.name, strId) > 0 Then
        findPath = strBase & "\" & folder.name
        Exit Function
    End If
Next folder

End Function

P.S. I'm sure someone will suggest modifying my folder structure so that I can programmatically predict the path but for various reason that isn't possible in my case.

A: You could use the FindFirstFile Win32 API, which allows you to search for files or sudirectories matching a specified name. Additionally, you could also use the FindFirstFileEx function, along with a FINDEX_SEARCH_OPS parameter of FindExSearchLimitToDirectories, which would limit your search to a file that matches a specified name and is also a directory (if the file system supports directory filtering). For more information on using these functions from VB/VBA see the following:
http://www.xtremevbtalk.com/showpost.php?p=1157418&postcount=4
http://support.microsoft.com/kb/185476
http://www.ask-4it.com/how-to-use-findfirstfile-win32-api-from-visual-basic-code-2-ca.html

A: Consider splitting traversing the folders from finding your key.  Instead of the instr test, store the folder names in a table, then use a query on the table to find your target.  It might be slower, but searching should be faster.


text:
Q: nginx short urls for mediawiki I am trying to do short URLs for a MediaWiki site. The wiki is in a subdirectory mydir (http://www.example.com/mywiki). I've already set up rewrites in /etc/nginx/sites-available so that example.com redirects to example.com/mywiki.
Currently the URL is like http://www.example.com/mywiki/index.php?title=Main_Page. I want to clean up the url so that it looks like http://www.example.com/mywiki/Main_Page. I am having quite a bit of trouble doing this. I am not familiar with regular expressions or the syntax that the nginx config files use.
This is what I currently have:
server_name example.com www.example.com;

location /
{
  rewrite ^.+ /mywiki/ permanent;
}

location /wiki/
{
  rewrite ^/mywiki/([^?]*)(?:\?(.*))? /mywiki/index.php?title=$1&$2 last;
}

The second rewrite is obviously the one that's broken. It is based off of Page title -- nginx rewrite--root access in the MediaWiki documentation.
When I try to load the site, the browser tells me I get infinite redirects. Does anyone who how I should go about fixing this issue? Or rather, what is the correct way to implement this, and what do all those symbols mean?

A: That's a very interesting expression they have there.  Their main manual page for short URLs has this to say:

These guides are old and are almost entirely bad advice.

Anyway, let's see if we can simplify it a bit.
rewrite ^/wiki/([^\?]*) /mywiki/index.php?title=$1&$args last;

Note that you can't overlay the 'pretty' path (which you've put in the location block, so let's run with it) and the physical path; the norm is to use /wiki/ as the pretty path (your $wgArticlePath config) and /w/ as the physical path (your $wgScriptPath config).
So, all in all, something like this:
location / {
  rewrite ^/$ /wiki/ permanent;
}

location /wiki/ {
  rewrite ^/wiki/([^\?]*) /mywiki/index.php?title=$1&$args last;
}

...and you'll need the PHP handling in some form as they've shown in their example, as well as to update your Settings.php with appropriate $wgScriptPath and $wgArticlePath settings, as well as setting $wgUsePathInfo to true.


text:
Q: PowerShell Workflow not running as intended I have a PowerShell script which I've converted to a Workflow. The script is near identical, except for the few lines that need to be altered in order for it to be a Workflow.
However, for some reason it doesn't output like I think it should, and I am absolutely clueless as to why this would be the case.
Original PS script:
$DynatraceTenantID = "asdf"
$DynatraceToken = "asdf"
$DynatraceServer = "asdf"

$TagName = "env"
$TagValue = "dynatrace"

$result_array_altered = @()
$result_array_installed = @()
$result_array_notaltered = @()

$vms = Get-AzureRmResource -TagName $TagName -TagValue $TagValue | Where-Object {$_.ResourceType -like "Microsoft.Compute/virtualMachines"} | Where-Object {$_.Name -inotlike "MyVMx0"}

Foreach ($vm in $vms) {
    $vm0 = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status
    $vm1 = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name
    $vm2 = $vm1.Extensions
    if ($vm2.Publisher -notcontains "dynatrace.ruxit"){
        if ($vm0.Statuses.DisplayStatus -eq "VM running") {
            Set-AzureRmVmExtension `
                -Name "Dynatrace" `
                -Publisher "dynatrace.ruxit" `
                -ResourceGroupName "$($vm1.ResourceGroupName)" `
                -Location "$($vm1.Location)" `
                -VMName "$($vm1.Name)" `
                -ExtensionType "oneAgentWindows" `
                -TypeHandlerVersion "2.3" `
                -Settings @{ "tenantId"=$DynatraceTenantID; "token"=$DynatraceToken;"server"=$DynatraceServer; }

            $objAltered = New-Object -TypeName PSObject -Property @{
                VMaltered = $($vm1.Name)
                IDaltered = $($vm1.Id)
                }

            $result_array_altered += $objAltered
            } else {
                $objNotAltered = New-Object -TypeName PSObject -Property @{
                    VMnotAltered = $($vm1.Name)
                    IDnotAltered = $($vm1.Id)
                }

                $result_array_notaltered += $objNotAltered
            }
        } else {
            $objInstalled = New-Object -TypeName PSObject -Property @{
                VMinstalled = $($vm1.Name)
                IDinstalled = $($vm1.Id)
            }

            $result_array_installed += $objInstalled
        }
    }

$result_array_altered | ConvertTo-Json

$result_array_installed | ConvertTo-Json

$result_array_notaltered | ConvertTo-Json

Outputs the following:
[
    {
        "IDinstalled":  "/subscriptions/MY-SUBSCRIPTION/resourceGroups/virtual-machines/providers/Microsoft.Compute/virtualMachines/MyVMw0",
        "VMinstalled":  "MyVMw0"
    },
    {
        "IDinstalled":  "/subscriptions/MY-SUBSCRIPTION/resourceGroups/virtual-machines/providers/Microsoft.Compute/virtualMachines/MyVMw1",
        "VMinstalled":  "MyVMw1"
    }
]

The converted PowerShell to PS Workflow:
workflow InstallDynatrace {
    $DynatraceTenantID = "asdf"
    $DynatraceToken = "asdf"
    $DynatraceServer = "asdf"

    $TagName = "env"
    $TagValue = "dynatrace"

    $result_array_altered = @()
    $result_array_installed = @()
    $result_array_notaltered = @()

    $vms = Get-AzureRmResource -TagName $TagName -TagValue $TagValue | Where-Object {$_.ResourceType -like "Microsoft.Compute/virtualMachines"} | Where-Object {$_.Name -inotlike "MyVMx0"}

    Foreach -parallel ($vm in $vms) {
        $vm0 = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status
        $vm1 = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name
        $vm2 = $vm1.Extensions
        if ($vm2.Publisher -notcontains "dynatrace.ruxit"){
            if ($vm0.Statuses.DisplayStatus -eq "VM running") {
                Set-AzureRmVmExtension `
                    -Name "Dynatrace" `
                    -Publisher "dynatrace.ruxit" `
                    -ResourceGroupName "$($vm1.ResourceGroupName)" `
                    -Location "$($vm1.Location)" `
                    -VMName "$($vm1.Name)" `
                    -ExtensionType "oneAgentWindows" `
                    -TypeHandlerVersion "2.3" `
                    -Settings @{ "tenantId"=$DynatraceTenantID; "token"=$DynatraceToken;"server"=$DynatraceServer; }

                $objAltered = New-Object -TypeName PSObject -Property @{
                    VMaltered = $($vm1.Name)
                    IDaltered = $($vm1.Id)
                    }

                } else {
                    $objNotAltered = New-Object -TypeName PSObject -Property @{
                        VMnotAltered = $($vm1.Name)
                        IDnotAltered = $($vm1.Id)
                    }

                }
            } else {
                $objInstalled = New-Object -TypeName PSObject -Property @{
                    VMinstalled = $($vm1.Name)
                    IDinstalled = $($vm1.Id)
                }

            }
        $workflow:result_array_altered += $objAltered
        $workflow:result_array_notaltered += $objNotAltered
        $workflow:result_array_installed += $objInstalled
        }

    $result_array_altered | ConvertTo-Json

    $result_array_installed | ConvertTo-Json

    $result_array_notaltered | ConvertTo-Json
}

Outputs the following:
PS C:\WINDOWS\system32> InstallDynatrace
[
    {
        "VMnotAltered":  "MyVMw1",
        "IDnotAltered":  "/subscriptions/MY-SUBSCRIPTION/resourceGroups/virtual-machines/providers/Microsoft.Compute/virtualMachines/MyVMw1",
        "PSComputerName":  "localhost",
        "PSShowComputerName":  true,
        "PSSourceJobInstanceId":  "36c288df-41c3-4b61-9a6c-445707f76bea"
    },
    {
        "VMnotAltered":  "MyVMw0",
        "IDnotAltered":  "/subscriptions/MY-SUBSCRIPTION/resourceGroups/virtual-machines/providers/Microsoft.Compute/virtualMachines/MyVMw0",
        "PSComputerName":  "localhost",
        "PSShowComputerName":  true,
        "PSSourceJobInstanceId":  "36c288df-41c3-4b61-9a6c-445707f76bea"
    }
]

Note how the original script shows that results array to be VMinstalled and IDinstalled, whereas the workflow shows as VMnotAltered and IDnotAltered, meaning that it saw the VMs as NOT having Dynatrace installed (line 19), didn't see it Running (line 20) and just added it to the Not Altered array.
Any ideas where I'm going wrong?
UPDATED FOR THEO ANSWER
PS C:\WINDOWS\system32>
workflow InstallDynatrace {
    $DynatraceTenantID = "asdf"
    $DynatraceToken = "asdf"
    $DynatraceServer = "asdf"

    $TagName = "env"
    $TagValue = "dynatrace"

    $result_array_altered = @()
    $result_array_installed = @()
    $result_array_notaltered = @()

    $vms = Get-AzureRmResource -TagName $TagName -TagValue $TagValue | Where-Object {$_.ResourceType -like "Microsoft.Compute/virtualMachines"} | Where-Object {$_.Name -inotlike "MyVMx0"}

    Foreach -parallel ($vm in $vms) {
        $vm0 = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status
        $vm1 = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name
        $vm2 = $vm1.Extensions
        if ($vm2.Publisher -ne "dynatrace.ruxit"){
            if ($vm0.Statuses.DisplayStatus -eq "VM running") {
                Set-AzureRmVmExtension `
                    -Name "Dynatrace" `
                    -Publisher "dynatrace.ruxit" `
                    -ResourceGroupName "$($vm1.ResourceGroupName)" `
                    -Location "$($vm1.Location)" `
                    -VMName "$($vm1.Name)" `
                    -ExtensionType "oneAgentWindows" `
                    -TypeHandlerVersion "2.3" `
                    -Settings @{ "tenantId"=$DynatraceTenantID; "token"=$DynatraceToken;"server"=$DynatraceServer; }

                $objAltered = New-Object -TypeName PSObject -Property @{
                    VMaltered = $($vm1.Name)
                    IDaltered = $($vm1.Id)
                    }

                $workflow:result_array_altered += $objAltered
                } else {
                    $objNotAltered = New-Object -TypeName PSObject -Property @{
                        VMnotAltered = $($vm1.Name)
                        IDnotAltered = $($vm1.Id)
                    }

                $workflow:result_array_notaltered += $objNotAltered
                }
            } else {
                $objInstalled = New-Object -TypeName PSObject -Property @{
                    VMinstalled = $($vm1.Name)
                    IDinstalled = $($vm1.Id)
                }

                $workflow:result_array_installed += $objInstalled
            }
        }

    $workflow:result_array_altered | ConvertTo-Json
    $workflow:result_array_installed | ConvertTo-Json
    $workflow:result_array_notaltered | ConvertTo-Json
}

InstallDynatrace
[
    {
        "VMnotAltered":  "MyVMw0",
        "IDnotAltered":  "/subscriptions/asdf/resourceGroups/virtual-machines/providers/Microsoft.Compute/virtualMachines/MyVMw0",
        "PSComputerName":  "localhost",
        "PSShowComputerName":  true,
        "PSSourceJobInstanceId":  "d23d8e5b-dc3c-475f-82fe-968a3eeef946"
    },
    {
        "VMnotAltered":  "MyVMw1",
        "IDnotAltered":  "/subscriptions/asdf/resourceGroups/virtual-machines/providers/Microsoft.Compute/virtualMachines/MyVMw1",
        "PSComputerName":  "localhost",
        "PSShowComputerName":  true,
        "PSSourceJobInstanceId":  "d23d8e5b-dc3c-475f-82fe-968a3eeef946"
    }
]

PS C:\WINDOWS\system32>

A: You have made the same error you did earlier I'm afraid.
Where in the script you add the object to the corresponding array where it should be added, namely right after creating it inside the if or else block, in the Workflow you add them all at the end of the loop..
This means that regardless of the outcome of the if {...} else {...} tests, you add them anyway.
This should do things in the right place:
Foreach -parallel ($vm in $vms) {
    $vm0 = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status
    $vm1 = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name
    $vm2 = $vm1.Extensions
    if ($vm2.Publisher -notcontains "dynatrace.ruxit"){  # should be -ne I think
        if ($vm0.Statuses.DisplayStatus -eq "VM running") {
            Set-AzureRmVmExtension `
                -Name "Dynatrace" `
                -Publisher "dynatrace.ruxit" `
                -ResourceGroupName "$($vm1.ResourceGroupName)" `
                -Location "$($vm1.Location)" `
                -VMName "$($vm1.Name)" `
                -ExtensionType "oneAgentWindows" `
                -TypeHandlerVersion "2.3" `
                -Settings @{ "tenantId"=$DynatraceTenantID; "token"=$DynatraceToken;"server"=$DynatraceServer; }

            $objAltered = New-Object -TypeName PSObject -Property @{
                VMaltered = $($vm1.Name)
                IDaltered = $($vm1.Id)
                }
            # this is where you add the object to the $workflow:result_array_altered array
            $workflow:result_array_altered += $objAltered
        }
        else {
            $objNotAltered = New-Object -TypeName PSObject -Property @{
                VMnotAltered = $($vm1.Name)
                IDnotAltered = $($vm1.Id)
            }
            # this is where you add the object to the $workflow:result_array_notaltered array
            $workflow:result_array_notaltered += $objNotAltered
            }
        }
    else {
        $objInstalled = New-Object -TypeName PSObject -Property @{
            VMinstalled = $($vm1.Name)
            IDinstalled = $($vm1.Id)
        }
        # this is where you add the object to the $workflow:result_array_installed array
        $workflow:result_array_installed += $objInstalled
    }
}

$workflow:result_array_altered    | ConvertTo-Json
$workflow:result_array_notaltered | ConvertTo-Json
$workflow:result_array_installed  | ConvertTo-Json

Then, at the end of the workflow, you outputted the arrays you still had in memory from the earlier script version ($result_array_altered | ConvertTo-Json etc. I have changed that to match the new arrays for you.
Also, isn't $vm2.Publisher just a single string? In that case, change the lines
if ($vm2.Publisher -notcontains "dynatrace.ruxit")

into
if ($vm2.Publisher -ne "dynatrace.ruxit")

(-notcontains checks a value in an array where -ne tests for the 'not-equalness' of a single object, so a string  in this case)

UPDATE
I MAY have found an answer for the unwanted extra information here
It may look ugly, but try this at the end of the workflow:
$workflow:result_array_altered    | Select-Object -Property * -ExcludeProperty PSComputerName, PSShowComputerName, PSSourceJobInstanceId | ConvertTo-Json
$workflow:result_array_installed  | Select-Object -Property * -ExcludeProperty PSComputerName, PSShowComputerName, PSSourceJobInstanceId | ConvertTo-Json
$workflow:result_array_notaltered | Select-Object -Property * -ExcludeProperty PSComputerName, PSShowComputerName, PSSourceJobInstanceId | ConvertTo-Json


text:
Q: Why can't I cast from a List to List? I have a List of objects, which are of my type QuoteHeader and I want to pass this list as a list of objects to a method which is able to accept a List<object>.
My line of code reads...
Tools.MyMethod((List<object>)MyListOfQuoteHeaders);

But I get the following error at design time...
Cannot convert type 'System.Collections.Generic.List<MyNameSpace.QuoteHeader>'
to 'System.Collections.Generic.List<object>'

Do I need to do anything to my class to allow this? I thought that all classes inherit from object so I can't understand why this wouldn't work?

A: You can't cast List<OneType> to List<OtherType> as it is actually the instances of the list you want to cast, as well as the List itself.
there is an extension method which will allow you to do this (MSDN reference):
IEnumerable<Object> myNewEnumerable = myEnumerable.Cast<Object>();

This method will attempt to cast each instance of the list of one type to the other type and add them to a new enumerable.  it will throw an exception if any instance can't be cast.
As far as the system is concerned the two types for your lists are just different types, so it is like saying:
A objectOfTypeA;
B objectOfTypeB = (B) objectofTypeA;

To be able to do the cast there would have to be an implicit or explicit conversion between the types available, which there isn't (unless you provided one, which you might be able to do).
you expect it to work because List<object> will always be able to hold any type in another list, but when you think about it in those terms you can see why it doesn't.
I'm sure there is a more technically competent answer, but that is the gist of it I think.
you might be interested in reading Eric Lippert's series on Covariance and Contravariance as this may be helpful to you.
This question may also be useful

A: List<MyClass> x = someList.Select(f => (MyClass)f).ToList();

A: The reason this is not legal is because it is not safe. Suppose it were legal:
List<Giraffe> giraffes = new List<Giraffe>();
List<Animal> animals = giraffes; // this is not legal; suppose it were.
animals.Add(new Tiger());  // it is always legal to put a tiger in a list of animals

But "animals" is actually a list of giraffes; you can't put a tiger in a list of giraffes.
In C# this is, unfortunately, legal with arrays of reference type:
Giraffe[] giraffes = new Giraffe[10];
Animal[] animals = giraffes; // legal! But dangerous because...
animals[0] = new Tiger(); // ...this fails at runtime!

In C# 4 this is legal on IEnumerable but not IList:
List<Giraffe> giraffes = new List<Giraffe>();
IEnumerable<Animal> animals = giraffes; // Legal in C# 4
foreach(Animal animal in animals) { } // Every giraffe is an animal, so this is safe

It is safe because IEnumerable<T> does not expose any method that takes in a T.
To solve your problem you can:

*

*Create a new list of objects out of the old list.

*Make the method take an object[] rather than a List<object>, and use unsafe array covariance.

*Make the method generic, so it takes a List<T>

*Make the method take IEnumerable

*Make the method take IEnumerable<object> and use C# 4.

A: I'm presuming that you mean that the lists are of types which inherit from each other or can otherwise be cast from one type to another - in that case, try this:
Tools.MyMethod(MyListOfQuoteHeaders.Cast<OtherType>());

A: Thanks for the many responses.
I'll explain what I wanted to do and what I've come up with as a solution.
I needed a method that I could call by passing in a List of objects of any type and then output that list to XML. Also passed to the method would be a string which would be a system file structure path location which points to the location the XML file would be saved to. As I have an ever growing number of classes and types, I wanted to avoid writing multiple methods to cater for each type of class. I'm not sure if I've even gone about this the right way, but it's a lightweight solution to my problem and works. If there are any issues with it, or if anyone has any comments please feel free...
So... my method now looks like this...
    public static Enums.Status WriteListToXML<T>(string outputPath, List<T> inboundList)
    {
        try
        {
            XmlSerializer xmlSerializer = new XmlSerializer(inboundList.GetType());
            using (StreamWriter streamWriter = System.IO.File.CreateText(outputPath))
            {
                xmlSerializer.Serialize(streamWriter, inboundList);
            }
            return Enums.Status.Success;
        }
        catch (Exception ex)
        {
            return Enums.Status.Failure;
        }
    }

... and my calling line reads...
WriteListToXML<QuoteHeader>(@"C:\XMLDocuments\output\QuoteHeaders.xml", quoteHeadersList);

Like I said, it may not be the tidiest solution, but it works well in my scenario.

A: The problem is that at Compile time, the compiler emits 2 separate classes, 1 that represents List<MyClass> and one that represents List<Object>. They are essentially 2 separate types. That's how Generic types work, in .Net at least.
Assuming this is .Net, you could do
MyListOfQuoteHeaders.Cast<Object>()

which basically does
var objects = new List<Object>();

foreach(var item in MyListOfQuoteHeaders)
{
   objects.Add((object)item);
}

return objects;


text:
Q: Dynamic URLs in CodeIgniter? How to get URLs like /user/bob user/martin dynamically in CodeIgniter?

A: You need to set up custom routing for the controller in application/config/routes.php, e.g.
$route['user/(:any)'] = "user/user_controller_method/$1";

A: you should use the
$route['user/(:any)'] = "user/user_controller_method/$1";

as James suggested, and then define the funcion on the user controller:
function user_controller_method($username) {
   // ... $username should be the url param
}


text:
Q: ModuleNotFoundError error while importing file in python I am getting "ModuleNotFoundError" when importing a python file.PFB the code:
testImport.ipynb
feet_in_miles=5280
meters_in_kilometer=1000
beatles=["John Lenon","PAul McCartney",""]

Modules.ipynb:
import testImport
print(testImport.beatles)

On running Modules.ipynb, I am getting the below error:

ModuleNotFoundError                       Traceback (most recent call last)
 in ()
----> 1 import testImport
2 print(testImport.beatles)
ModuleNotFoundError: No module named 'testImport'

Kindly let me know what's the issue.

A: check in your directory that testImport.py is in the folder where you are running the code . New program should be in same directory


text:
Q: Java Android - Background Clipboard Service Im trying to do a background clipboard listener service,
that when detects a url on clipboard show some options.
There its my service code:
public class MyService extends Service {
....
public int onStartCommand(Intent intent, int flags, int startId){
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        String data2check = ((String) clipboard.getText());
        try {
            checkPaste("data2check");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
}
....

But in all ways that I try I receives always the same error:
Attempt to invoke virtual method

I think that the problem its that I cant access to getSystemService from a service.
If anyone can help me, thanks.

A: Remove double quotes at checkPaste("data2check").
Try below code:
     public class MyService extends Service {
     ....
         public int onStartCommand(Intent intent, int flags, int startId){
         ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    String data2check = ((String) clipboard.getText());
    try {
        checkPaste(data2check);//edited line
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
 }


text:
Q: XmlDocument.LoadXml() and entities Using XmlDocument.LoadXml(), how can I load a string with & or < in it?
For instance, the following string causes an error:
<choice id="A1"> sample < text</choice>
Do I need to use a Resolver somehow? Can XmlDocument even handle things like this?


text:
Q: Getting Duration of Two DateAndTime in(HH:mm:ss) Format Based on Some Conditions duration of DateAndTime in(HH:MM:SS) but i need to select startdate and Enddate by sorting some conditions but duration is getting wrong
Start Date                     End date                  Duration
 2018-11-22 17:34:33.00   2018-11-26 10:22:57.00      09:36:48.0000000

in the above example DateDiffrence is 98 hours, but its calculated as 9 hours??
(SELECT CONVERT(TIME, DATEADD(s, SUM(( DATEPART(hh, (B.DateAndTime - A.DateAndTime)) * 3600 ) + ( DATEPART(mi, (B.DateAndTime - A.DateAndTime)) * 60 ) + DATEPART(ss, (B.DateAndTime - A.DateAndTime))), 0)) AS total_time
FROM (SELECT DateAndTime, ROW_NUMBER() OVER (ORDER BY DateAndTime ASC) AS S
      FROM Tablename
      WHERE Marker='S'
      and TagIndex=2
      AND a.Val=Val) AS A
INNER JOIN
(SELECT DateAndTime, ROW_NUMBER() OVER (ORDER BY DateAndTime ASC) AS E
 FROM Tablename
 WHERE Marker='E'
 and TagIndex=2
 AND a.Val=Val) AS B
ON B.E=A.S) AS Duration)

A: You can use something like this:
SELECT RIGHT(CONVERT(varchar,(DATEDIFF(s,'2018-11-22 17:34:33.00','2018-11-26 10:22:57.00')) / 3600 ),2) + ':'
          + RIGHT(CONVERT(varchar,(DATEDIFF(s,'2018-11-22 17:34:33.00','2018-11-26 10:22:57.00')) / 60) % 60 ,2) + ':'
          + RIGHT(CONVERT(varchar,(DATEDIFF(s,'2018-11-22 17:34:33.00','2018-11-26 10:22:57.00')) % 60 ),2)


text:
Q: Open Source Library for sending emails via gmail (smtp.gmail.com) using SMTPS (TLS) Note: If you dont have time to read this long journey, the solution (with sourcecode) is here: http://www.coastrd.com/smtps.
For a long time sending email uing SMTP (port 25) via a remote mail server (usually at the website hosting company) was easy to do with an application. Open a TCP port 25, send "HELO ..." etc
To do this using googles email service is giving me a problem because they insist on using port 465 SMTPS ie SMTP with TLS encryption:
http://en.wikipedia.org/wiki/Transport_Layer_Security#How_it_works
In researching a way to do this with a language like C++ or a flavor of basic, i came across:
http://forums.realsoftware.com/viewtopic.php?f=2&t=29542
http://forums.realsoftware.com/viewtopic.php?f=2&t=26959&p=162671#p162671
and a Python question:
python smtp gmail authentication error (sending email through gmail smtp server)
If I am understanding this correctly, I am going to need to implement the TLS encryption in my C++ code, complete with all the hand shaking and negotiation?
From the C# question:
sending email with gmail smtp ( secure layer ) in c++
This library does not do it
http://johnwiggins.net/jwsmtp/
ADDED:
A lot of people are just installing the stunnel as a service and then configuring it to manage the an SSL connection
http://www.stunnel.org/about/
Stunnel is an OpenSSL wrapper. OpenSSL has some perfomance issues (http://josefsson.org/gnutls4win/)
"Initializing libgcrypt takes a long time on some systems, there has been reports that it can take around 10 seconds."
and requires: "libeay32.dll" 1.35MB + "libssl32.dll" 310k + "zlib1.dll" 75k
Then thre are a couple of commercial products:
http://www.chilkatsoft.com/downloads.asp
This product is mostly delivered as an Activex (COM) "dll" (requiring an installer on the users machine to 'register' the dll - another bad .net idea).
The installer loads "ChilkatMime.dll" 1.33Mb, "ChilkatCert.dll" 1.26MB, "ChilkatUtil.dll" 720k. The developers were not at all interested in cooperating on a true C .dll library that could be called from any language including C/C++/BASIC/Python etc etc. Given their attitude I am not surprised they have been the victim of code generators made by hackers.
Apart from the cheesy name and artwork, their products are reasonably priced, but the one I tried, connected on port 25 despite being told to use port 465.
By contrast, a commercial option from catalyst:
http://www.catalyst.com/products/sockettools/secure/library/index.html
is now available as component of the main socket tools product for 1/3 the price. These tools are first class! yes, you get what you pay for. The developers are responsive and open to suggestions. They offer ALL flavors of dll including a stand alone .dll that can be shipped with you product that is only 230k! For commecial solutions they win hands down.
An SLL/TLS connection can be made explicitly (as soon as the handshake begins the seesion) or implicitly (after the handshake using STARTTLS etc)
CodeIgniter is implicit for example (as are options in Python, asp, php etc)
http://codeigniter.com/forums/viewthread/84689/
Once the connection has been made, a "tunnel" exists through which a MIME session may proceed:
  "EHLO " + sLocalHost + CRLF
  "MAIL FROM: " + sMailFrom + CRLF
  "RCPT TO: " + "me@mydomain.com" + CRLF
  "DATA: Testing, Testing xyz" + CRLF
  CRLF + "." + CRLF
  "QUIT"

with the usual responses from the server.
Some languages handle the MIME communication for you (socket tools, codeigniter, etc) and you just feed in the email subject, body and address making it very easy to use
CryptLib is an open source solution that facilitates an SSL/TLS tunnel with a C style .dll in only 1MB (full compilation). Since the source is available, it is possible to compile a version of the dll with just the components you need that should come in somewhat less than that.
http://www.cs.auckland.ac.nz/~pgut001/cryptlib/download.html
The author was very responsive even though I got the library to work immediately and was asking about the MIME dialog. There is 330 page manual! Thank you.
THis library is not an MTA (mail transfer agent) so you must write the MIME conversation above, but it is FREE!
source code available here:
http://www.coastrd.com/smtps.

A: Check out http://sourceforge.net/projects/libquickmail/ .
This library can send mail with optional attachments to multiple recipients.
The SMTP transport relies on libcurl, so it supports things like authentication and TLS.
The C API is very simple to use.
Tested on Linux (GCC) and Windows (MinGW) but should work on any platform where libcurl is available.

A: You are correct that you'll need to enable TLS in your application.  Instead of doing this on your own, I'd suggest looking into OpenSSL.
Additionally, You need to enable SMTP in your account and support SMTP authentication to send traffic through Gmail.
There is also a duplicate question that has some pointers and a C# implementation with code that might be able to help you out.
There is also a library that might be easier to use than rolling your own (although it doesn't currently have TLS support).


text:
Q: How do I make my image placeholders show up using CSS grid? I'm currently trying to figure out why my blank image placeholders aren't showing up when I use CSS grid. No matter what selectors I use and how I use them, I can't seem to figure out how to make it appear.
I've tried messing around with the class selectors and styles to make it appear, but I've been getting no luck in getting it to pop up. This is my current code right now revolving around the image placeholders:
.story {
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-start;
    align-items: flex-start;
    align-content: flex-start;
    gap: 1.618rem;
}

.story:nth-child(even) {
    flex-direction: row-reverse;
}

.story .image {
    aspect-ratio: 1;
    background-color: #dadada;
    flex: 0 0 calc(50% - 1.618rem);
}

.story .description {
    flex: 1 0 50%;
}

@media screen and (min-width: 576px){
    .story .image {
        flex-basis: 30%;
    }
}

@media screen and (min-width: 992px){
    .story,
    .story:nth-child(even) {
        flex-flow: column wrap;
    }

    .story .image {
        aspect-ratio: 16/9;
        flex: 0 0 100%;
        width: 100%;
        background-color: blue;
    }
}

And my HTML:

Articles

Image

Story Name

Lorem ipsum...

                            Link

Image

Story Name

Lorem ipsum...

                            Link

Image

Story Name

Lorem ipsum...

                            Link

Please help me understand what I am doing wrong! T_T


text:
Q: Enable keyboard backlight on Dell G15 5510 I'm new at using Ubuntu and new to Ask Ubuntu. I just started using Ubuntu a couple of days ago.
I can't turn on the keyboard backlight. I know on Windows Edition, Dell G15 5510 has an app called "Alienware Command Center" to control the lights. Is there any app or configuration that I can use to turn on or configure my keyboard lights?
I have tried to change my xorg.conf
# nvidia-settings: X configuration file generated by nvidia-settings
# nvidia-settings:  version 470.57.01

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0" 0 0
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
    Option         "Xinerama" "0"
EndSection

Section "Files"
EndSection

Section "Module"
    Load           "dbe"
    Load           "extmod"
    Load           "type1"
    Load           "freetype"
    Load           "glx"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    # HorizSync source: edid, VertRefresh source: edid
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "AU Optronics Corporation"
    HorizSync       195.0 - 195.0
    VertRefresh     60.0 - 165.0
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BoardName      "NVIDIA GeForce RTX 3060 Laptop GPU"
    Option "RegistryDword" "EnableBrightnessControl=1"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    Option         "Stereo" "0"
    Option         "nvidiaXineramaInfoOrder" "DFP-5"
    Option         "metamodes" "nvidia-auto-select +0+0"
    Option         "SLI" "Off"
    Option         "MultiGPU" "Off"
    Option         "BaseMosaic" "off"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

My PC specs: Dell G15 5510 Edition: RTX 3060 laptop, i7 11h


text:
Q: non- Static method Reference error Ok so in my mail class im calling

public class Main extends JavaPlugin {
    @Override
    public void onEnable () {
    getLogger().info("Loading configs...");
        Hud.startHud();
    }
    @Override
    public void onDisable () {

    }
}

and it give me
non-static method cannot be referenced from static context

public class Hud extends JavaPlugin {
    public void startHud () {
        ScoreboardManager manager = Bukkit.getScoreboardManager();
        Scoreboard board = manager.getNewScoreboard();
        Team team = board.registerNewTeam("teamname");
        Objective objective = board.registerNewObjective("test", "dummy");
        Score score = objective.getScore(ChatColor.GREEN + "Kills:"); //Get a fake offline player
        score.setScore(1);
    }
}

A: Make startHud() a static method. else call it like new Hud().startHud();


text:
Q: Angular JS watch won't fire when data is changed in stomp subscribe below i will paste my ws connection code:
function connect() {
    var socket = new SockJS('http://localhost:8080/gs-guide-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log('Connected: ' + frame);
        stompClient.subscribe('/events/get/1', function (event) {
             $scope.event = JSON.parse(event.body).path + ": " + JSON.parse(event.body).eventType;
        });
    });
}

And this code above is inside controller:
myApp.controller('ConnectionController', ['$scope', function($scope) {

And below is my directive to listen on change:
myApp.directive('listenerEventsDirective', function() {
    return{
        restrict: 'E',
        scope: {
            event: '='
        },
        link: function(scope, element) {
            scope.$watch('event', function(newValue, oldValue) {
                if(newValue){
                    element.append("
" + newValue + "
");
                    alert("newValue " + newValue);
                }
            });
        }
    }
});

If i declare method like this in controller:
$scope.changeEvent = function(change){
    this.event = change;
}

everything is working, but if i try to update my value through ws subscribtion it won't work.
How can i make watch fires even if i'm changing event in stomp subscribe method?

A: your callback is called outside angular, try wrapping it in an $apply method in order to trigger a digest cycle to determine changes:
$scope.$apply(function () {
   $scope.event = JSON.parse(event.body).path + ": " +
      JSON.parse(event.body).eventType;
});


text:
Q: I want to color the result of a search I want to color the result of a search

A: Use an NSAttributedString and give the words you want to color a foreground color attribute.

A: I hope this logic gets you well....
You can store all the text in and array of words separating them by the "space" and the use the compare function in swift and then perform task according to that so that you can change the colour of that particular word.
I hope this logic can be helpful. if you need any more clarification let me know cheers :)


text:
Q: Sprites is not loading in Ad-HOC mode in iOS I am completely stumped here. Created my game, all working in XCode' simulator and also on my device when directly deployed from XCode.
I Submitted my app and they rejected it and asked me to run in Ad-HOC mode in my device to test since the app was not working.
I can replicate the issue in Ad-HOC mode.

Issue: Once replace scene is invoked, the tile map is not populating
  the Sprites from the sprite-sheet created using the TexturePacker
  software. The app does not crash, however the Scene is empty with just
  the background without any Sprites loaded in it.

Not sure how can this be a code issue since works fine when I install directly from XCode.
Please help, thanks in advance :)

A: @LearnCocos2D, Thanks, I found out the bug last night. I did not use CC_CONTENT_SCALE_FACTOR() when placing sprites using tilemap co-ordinates. Amazing thing is, it worked in debug mode but did not as soon as I released the binary :)


text:
Q: Rows Data into column data having the month and year I have data as shown below:
server_name     database_name   totaldb_size_megs   MonthYear
NAULNSQD003 DBAInfo 18  Aug-18
NAUSPLNSQD003   master  6.4375  Aug-18
NALNSQD003  model   33  Sep-18
NAUSPQD003  msdb    15.6875 Aug-18
NAUSSQD003  tempdb  824 Aug-18
NAUQD003    DBAInfo 18  Sep-18

How to achieve it in below format.
Columns and rows:
Servername  Dataabse name    Aug    Sep     Growth
Servername    Dbname        Dbsize  Dbsize  Aug-Sep

I have tried pivot but unable to get it
select MODIFDT,OldItemNumber from
(
  select  MODIFDT,OldItemNumber,rowid,ShortDescription
  from cdvtool..itemmaster

) d
pivot
(
  max(rowid)
  for ShortDescription in (MODIFDT,OldItemNumber)
) piv

And have a logic of: If I query it for current month(March), i need to get the details of the previous two months data

A: As shown in the linked question, this is just pivoting and conditional aggregation:
SELECT ServerName,
       DatabaseName,
       MAX(CASE WHEN MonthYear = '20180801' THEN TotalDBSize END) AS AugSize, --Used a date, as not sure what data type your "MonthYear" really is
       MAX(CASE WHEN MonthYear = '20180901' THEN TotalDBSize END) AS SepSize, --Used a date, as not sure what data type your "MonthYear" really is
       MAX(CASE WHEN MonthYear = '20180801' THEN TotalDBSize END) - MAX(CASE WHEN MonthYear = '20180901' THEN TotalDBSize END) AS Growth
FROM dbo.YourTable
GROUP BY ServerName,
         DatabaseName;


text:
Q: Django rest framework saving thumbnail image I've recently started developing with django + python and everything was going very smooth until I got stuck into a problem that probably is very simple but I can not solve with my inexperience with the framework/language.
I'm receiving an JSON object through an HTTP Request which contains some data and 2 pictures. Prior to those 2 pictures I wanted to save a thumbnail from one of them but I don't see to get that task done. I can save all the data easily including the 2 images. But I can not see to find a way to generate a way an have that in the DB also, as well the folder structure that I want.
My folders should look like:
pictures
   user
      originals
      processed
      thumbnails
   otherUser
       originals
       processed
       thumbnails

My goal is: Receive 2 pictures, create a thumbnail from one of them and them save all 3 pictures in 3 separate folders and the path to the Database.
Here's how my model code looks like.
class SomeData(models.Model):
    owner = models.ForeignKey('auth.User', related_name='canopeo_data')
    adjustments = models.CharField(max_length=10)
    latitude = GeopositionField()
    longitude = GeopositionField()
    notes = models.TextField(null=True, blank=True)
    original_image = models.ImageField(upload_to=original_image, max_length=255, blank=True)
    processed_image = models.ImageField(null=False, upload_to=processed_image, max_length=255)
    thumbnail_image = models.ImageField(null=False, upload_to=thumbnail_image, max_length=255)
    date_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('date_time',)

    def save(self, *args, **kwargs):
        super(SomeData, self).save(*args, **kwargs)

def original_image(self, filename):
    url = "pictures/%s/originals/%s" % (self.owner.username, filename)
    return url

def processed_image(self, filename):
    url = "pictures/%s/processed/%s" % (self.owner.username, filename)
    return url

def thumbnail_image(self, filename):
    url = "pictures/%s/thumbnail/%s" % (self.owner.username, filename)
    return url

Serializer code...
class SomeDataSerializer(serializers.HyperlinkedModelSerializer):
#url = serializers.HyperlinkedRelatedField(view_name='data', format='html')
owner = serializers.Field(source='owner.username')
thumbnail_image = serializers.Field(source='original_image')

class Meta:
    model = SomeData
    fields = ('url', 'adjustments', 'latitude', 'longitude', 'notes', 'original_image', 'processed_image',)

View code...
class SomeDataViewSet(viewsets.ModelViewSet):
queryset = SomeData.objects.all()
serializer_class = SomeDataSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

def pre_save(self, obj):
    obj.owner = self.request.user

I've tried many things such as easy_thumbnails, sorl_thumbnail, and some pre made methods on how to do it.. but I can't see to find a solution specific for what I've been wanting.
Thank you very much!

A: Looks like you have mistake in definition of the SomeDataSerializer. In model SomeData field original_image defined as ImageField, but in serialiser it's just Field, not ImageField. You should use correct field type:
class SomeDataSerializer(serializers.HyperlinkedModelSerializer):
    #url = serializers.HyperlinkedRelatedField(view_name='data', format='html')
    owner = serializers.Field(source='owner.username')
    thumbnail_image = serializers.ImageField(source='original_image')
    ...