text:
Q: Symfony2 Controller is not callable I've got this error:

Controller
  "Superplanner\UserBundle\Controller\RestController::afterResetAction"
  for URI "/afterreset" is not callable.

routing:
after_reset:
    defaults: { _controller: "UserBundle:Rest:afterReset" }
    path : /afterreset

security:
- { path: ^/afterreset, role: IS_AUTHENTICATED_ANONYMOUSLY }

method from RestController.php (from my UserBundle):
public function afterResetAction(Request $request)
{
    return new JsonResponse(array('Success' => 200, 'Response' => 'ok'), 200);
}

What is wrong with that?!
P.S. Yes, I've cleared cache

A: Did you try, using the method without that Request parameter?
public function afterResetAction()
{
    return new JsonResponse(array('Success' => 200, 'Response' => 'ok'), 200);
}

If you want to get the request from inside the controller, you can do this:
$request = $this->get('request');


text:
Q: Address State and Country not visible on the records Dear friends I have an interesting problem.
The address fields are not correct visible on the records.
On the account page I see all address fields, but on the Address record and Service Territory I cannot see the State and Country fields.
BUT, on the other sandbox I have not this problem.
All settings are the same on the both sandboxes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Want to make Excel file heading bold I want to make the Excel file heading as bold.
In below code I clearly mentioned the headings that I want to make bold:
excel_document = openpyxl.load_workbook(r"trial.xlsx", data_only=True)
sheet = excel_document["Sheet1"]
wb = openpyxl.Workbook()
sheets = wb.active
#Following are the headings, i want to make bold
sheets.cell(row=1, column=1).value="Device Type"
sheets.cell(row=1, column=2).value="Device ID"
sheets.cell(row=1, column=3).value="Status"

A: from openpyxl.styles import Font

bold_font = Font(bold=True)

For individual cells, you could do
sheets.cell(row=1,column=1).font = bold_font

Or, as in your case, if you want to set an entire row,
# ["1:1"] for the first row
for cell in sheets["1:1"]:
    cell.font = bold_font

See the documentation for more information on using styles.


text:
Q: Odoo-Creation sequence based on PostgreSQL sequence I am working with odoo 14 and I want to customize sale.order number generation. So, I want to create new sequence (ir.sequence) based on PostgreSQL database sequence object.
Do you have any idea?
Thank you for your help.
SAAD

A: from odoo import api, fields, models
import psycopg2
class ventes(models.Model):
_inherit = ['sale.order']
company = fields.Char()

name = fields.Char(string='Order Reference')

#Connection a la base de donnees
def open_conn(self):
    try:
        connection = psycopg2.connect(user="user",
                                      password="xxxxxxxxxxxxxx",
                                      host="192.168.1.1",
                                      port="5432",
                                      database="ventes")

        print("Using Python variable in PostgreSQL select Query")
        cursor = connection.cursor()
        postgreSQL_select_Query = "select nextval('myOdoo')"

        cursor.execute(postgreSQL_select_Query)
        row = cursor.fetchone()
        return  row[0]

    except (Exception, psycopg2.Error) as error:
        print("Error fetching data from PostgreSQL table", error)

    finally:
        # closing database connection
        if connection:
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed \n")

@api.model
def create(self, vals):
    num = self.open_conn()
    vals['name'] = num
    result = super(ventes, self).create(vals)
    return result


text:
Q: Can I use both dotnet and node in Azure Functions 2.0? As Durable Functions JS API is limited by now, I wonder can I write my orchestration code with C# Scripts and my activity functions with node in Azure Functions 2.0?

A: We're about to publish a v2 Functions release that removes the ability to run multiple languages in a single Function app. Going forward, all functions within a Function app must be written in the same language. (Note that v1 Function apps will not be affected by this.)
We're aiming to announce General Availability of Durable Functions JS later this year, which will include the rest of the API. The workaround we recommend at present is similar to what's documented here. In your case, you could expose some JavaScript APIs over HTTP and have C# activity functions invoke them from the Function app that contains your C# orchestrator.

A: Update
New release has published, function app requires single language right now. So this method is no longer valid.

You probably are talking about this limit as in JS some C# API is not implemented yet and some won't be implemented.
We can call JS Activity in C# orchestration function. Just test with a simple activity returns string, works as expected.
For local development, FUNCTIONS_WORKER_RUNTIME(in local.settings.json) specifies our function app language worker, only functions corresponding to this runtime can be recognized by function host. For example, in dotnet runtime, js functions are ignored.

*

*Delete FUNCTIONS_WORKER_RUNTIME and the host is able to work with different languages.

*Add one folder named after your Activity function to function app folder, containing function.json and index.js. See illustration below(In VSCode, similar to VS).

*Add CopyToOutputDirectory action to functionappname.csproj.
<ItemGroup>
...
    <None Update="MyJsActivity\index.js">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="MyJsActivity\function.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
</ItemGroup>

*Feel free to install node module if needed, remember to add CopyToOutputDirectory action for package.json, so that we can install modules using it during deployment.
Besides on portal there's no such equivalent setting right now, host offers different language workers by default. After deployment, everything should work.


text:
Q: Issues creating/using a simple U.S. to Metric converter. (HTML/JavaScript) Function is not firing All this program should/needs to do is do simple conversions between US & Metric, however, for some reason it is resisting every effort I have made to make it work. From what I can tell my script is not firing, I have worked relentlessly to fix it but my lack of experience with JS has made it an uphill battle. My HTML and JS appear to be in good order, so it must be my understanding of what I've written that is failing me.
The values for calculation come straight from Google, so they should be solid.

function calc()
{
 var h;
    var ee = isNaN(document.getElementById("number")).value;
    if (ee == "true")
    {
        document.writeln("Please use only numerical keys I.E 128");
    }
    else if (document.getElementById("us").value == 1)
    {if (document.getElementById("met").value == 4)
    {
        h = (document.getElementById("number").value * 453.592;
        document.writeln(document.getElementById("number").value + " pounds is" + h + "grams.");
    }
    else
        document.writeln("This is not a valid conversion!")
    }
    else if (document.getElementById("us").value == 2)
    {if (document.getElementById("met").value == 5)
    {
        h = (document.getElementById("number").value * 0.946353;
        document.writeln(document.getElementById("number").value + " liters is" + h + "quarts.");
    }
    else
        document.writeln("This is not a valid conversion!");
    }
    else if (document.getElementById("us").value == 3)
    {if (document.getElementById("met").value == 6)
    {
        h = (document.getElementById("number").value * 2.54;
        document.writeln(document.getElementById("number").value + " inches is" + h + "centimeters.");
    }
    else
        document.writeln("This is not a valid conversion!");
    }

}
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>U.S. to Metric Converter</title>

    <form>
        <input type="text" id="number">
        <select name="U.S." id="us">
            <option value="1">Pound(s)</option>
            <option value="2">Quart(s)</option>
            <option value="3">Inch(es)</option>
        </select>
        to
        <select name="Metric" id="met">
            <option value="4">Gram(s)</option>
            <option value="5">Liter(s)</option>
            <option value="6">Centimeter(s)</option>
        </select>
        </form>
    <button type="button" id="btn" onclick="calc()">Convert!</button>

Please be ruthless with me if I am being a complete idiot somewhere in here, my main priority is getting this working but a better understanding of where I am failing is definitely important.

A: Your Javascript has errors. You are missing the right bracket from a few expressions, e.g.:
h = (document.getElementById("number").value * 453.592; <-- add ) before ;

I suguest you try using a Javascript debugger such as Firebug, Chrome or IE Dev Tools, etc.
Have fun!

A: If you look closely on this line:
h = (document.getElementById("number").value * 453.592;

There is an unnecessary (. Get rid of that in all places where you have this code and your code will work.
Working Code Snippet:

function calc()
{
 var h;
    var ee = isNaN(document.getElementById("number")).value;
    if (ee == "true")
    {
        document.writeln("Please use only numerical keys I.E 128");
    }
    else if (document.getElementById("us").value == 1)
    {if (document.getElementById("met").value == 4)
    {
        h = document.getElementById("number").value * 453.592;
        document.writeln(document.getElementById("number").value + " pounds is" + h + "grams.");
    }
    else
        document.writeln("This is not a valid conversion!")
    }
    else if (document.getElementById("us").value == 2)
    {if (document.getElementById("met").value == 5)
    {
        h = document.getElementById("number").value * 0.946353;
        document.writeln(document.getElementById("number").value + " liters is" + h + "quarts.");
    }
    else
        document.writeln("This is not a valid conversion!");
    }
    else if (document.getElementById("us").value == 3)
    {if (document.getElementById("met").value == 6)
    {
        h = document.getElementById("number").value * 2.54;
        document.writeln(document.getElementById("number").value + " inches is" + h + "centimeters.");
    }
    else
        document.writeln("This is not a valid conversion!");
    }

}

    <meta charset="utf-8" />
    <title>U.S. to Metric Converter</title>

    <form>
        <input type="text" id="number">
        <select name="U.S." id="us">
            <option value="1">Pound(s)</option>
            <option value="2">Quart(s)</option>
            <option value="3">Inch(es)</option>
        </select>
        to
        <select name="Metric" id="met">
            <option value="4">Gram(s)</option>
            <option value="5">Liter(s)</option>
            <option value="6">Centimeter(s)</option>
        </select>
        </form>
    <button type="button" id="btn" onclick="calc()">Convert!</button>


text:
Q: iphone phonegap google maps memory warning I have an app written in Cordova (Phonegap) 2.3.0.
I use Jquery 1.8.2 and jquerymobile 1.2.0 and google maps v3.
XCode version 4.6
On one page I load a bunch of coordinates and creates different polylines added to the map.
There are 37 polylines added to the map and each polyline contains from 20 to 200 coordinates. About 1700 coordinates total on the map.
I also have like 20 markers.
The app works fine from start, I can zoom in and out and the map responds well, but if I reload the map I sometimes start to get messages like "Received memory warning" in XCode and the map wont update any more and sometimes the app crasch.
This is my clear routine that I call before adding the updated data:
function clearOverlays() {
try {

    if (polyLinesArray != null) {
        for (var i = 0; i < polyLinesArray.length; i++) {
            polyLinesArray[i].setMap(null);
            polyLinesArray[i] = null;

        }
        polyLinesArray.length = 0;
    }

}

catch(e) {
    handleError(e, "clearOverlays");
}

}
polyLinesArray is an array to which I push all polylines after they are added to the map.
So the question is, how can I clear the map in a good way the prevents memory warning (and leaks?)?
I have mouse click listeners too on the polylines, do I need to clear them as well before updating?
The same can occur when I navigate to another html-page in the app. After a few times forward and backward the map wont update any more. Before I navigate to other pages I call my clear routines first.
Another simple test done:
I just load the map, add my polylines and some other markers. Zoom in and out a few times and then the "Received memory warning" appears. I have not done anything else, just let google maps handle the zooming and panning around.
Regards
Henrik

A: I had the same issue and found out that it had to do with the way the Google Maps API draws overlays. For some reason this became too memory intensive from API 3.7 and up. Luckily in 3.12 (current experimental version) this seems to be resolved again. At least in my case.
If you call the maps api with &v=3.exp in the URL, your issue might be resolved as well.


text:
Q: LeakSanitizer in macos:  for objective-c function in stacktrace clang is:
└──( /opt/homebrew/Cellar/llvm/13.0.1_1/bin/clang++ --version
Homebrew clang version 13.0.1
Target: arm64-apple-darwin21.1.0
Thread model: posix
InstalledDir: /opt/homebrew/Cellar/llvm/13.0.1_1/bin

ASAN_OPTIONS is detect_stack_use_after_return=false detect_leaks=1
CMakeLists.txt has:
    add_compile_options(-fsanitize=address -fsanitize=leak -g)
    add_link_options(-fsanitize=address)

after the program exits, lots of leaks report, but in stacktrace, all objective-c function show as <unknown module>, and the address 0x3f368001a2e367b4 also seems wrong:
Direct leak of 40 byte(s) in 1 object(s) allocated from:
    #0 0x10343b678 in wrap_malloc+0x8c (libclang_rt.asan_osx_dynamic.dylib:arm64+0x3f678)
    #1 0x19ff4d638 in _Block_copy+0x3c (libsystem_blocks.dylib:arm64+0x1638)
    #2 0x3f368001a2e367b4  (<unknown module>)
    #3 0x5c5b8001a2e363c4  (<unknown module>)
    #4 0xea608001a2dec090  (<unknown module>)
    #5 0x8e440001a2debf14  (<unknown module>)
    #6 0x875a8001a2debdd0  (<unknown module>)
    #7 0x2498001a2debd28  (<unknown module>)
    #8 0x2a408001a2e3eab8  (<unknown module>)
    #9 0x731e8001a31bbce4  (<unknown module>)
    #10 0x48600001029f37dc  (<unknown module>)
    #11 0x102942cac in bgfx::gl::RendererContextGL::setRenderContextSize(unsigned int, unsigned int, unsigned int) renderer_gl.cpp:3475
    #12 0x1028f97d0 in bgfx::gl::RendererContextGL::init(bgfx::Init const&) renderer_gl.cpp:1817
    #13 0x1028f9024 in bgfx::gl::rendererCreate(bgfx::Init const&) renderer_gl.cpp:4044
    #14 0x102865bc0 in bgfx::rendererCreate(bgfx::Init const&) bgfx.cpp:2606
    #15 0x102866714 in bgfx::Context::rendererExecCommands(bgfx::CommandBuffer&) bgfx.cpp:2657

but while debugging, these symbols are correct shown in debugger:

so how to make them right in LeakSanitizer's report? thanks very much.


text:
Q: Replacing matrix rows for a vector without using a loop Is it possible to replace some rows of a matrix for specific vectors (in my case, random vectors) without using a loop in MATLAB?
Given:
A = [1 2 3;
     4 5 6;
     7 8 9;
     10 11 12]

I want to replace A([2 3],:) with, for instance, v = rand(1,3) but I really want that each chosen row (in this case 2 and 3) of A is randomly generated.
The problem with this is that I want to generalize it to do it for every given matrix A without using a loop in MATLAB. Is it possible?
Thank you.
Rui Semeano

A: How about:
A([2 3],:) = rand(2,size(A,2));

You get the number of columns in A by size(A,2), and then create a random matrix with the needed size and just assign it to the A.
If you want also to choose the rows randomly, then for N rows you can write:
N = 2;
randRows = randperm(size(A,1),N);
A(randRows,:) = rand(N,size(A,2))

P.S - if you want to randomize integers, use randi.

A: It sound like you want to generate the [2,3] randomly? I wasn't sure so I just named everything verbosely and made everything random.
MinimumInteger = 1;
MaximumInteger = 12;
NumberOfRows = 4;
NumberOfColums = 3;

A = randi([MinimumInteger, MaximumInteger], NumberOfRows, NumberOfColums);

NumberOfRowsToChange = randi([0, NumberOfRows]);

RowsToChange = randperm(NumberOfRows, NumberOfRowsToChange);

A(RowsToChange, :) = randi([MinimumInteger, MaximumInteger], NumberOfRowsToChange, NumberOfColums);


text:
Q: AJAX data uploading but not storing in database please help me! i'm uploading multiple data with ajax request and data is uploading and i get response 200 OK but there's no data stored into database. here's my store method.
$data = json_decode($request["final_json"], true);
$data_to_insert = [];

        foreach($data as $request){

                $data_to_insert = [
                 'office_name' => $request['office_name'],
                 'registration_number' => $request['registration_number'],
                 'owner' => $request['owner_name'],
                 'father_name' => $request['father_name'],
                 'address' => $request['address'],
                 'vehicle_class' => $request['vehicle_class'],
                 'insurance_type' => $request['insurance_type'],
                 'insurance_company_name' => $request['insurance_company_name'],
                 'insurance_from' => $request['insurance_from'],
                 'insurance_up_to' => $request['insurance_up_to'],
                 'policy_number' => $request['policy_number'],
                ];
          }
       DB::table('owners')->updateOrInsert(['chasis_number' => $request['chasis_number']], $data_to_insert);

request is complete and it takes time too depending how much data i upload but in database there's not a single row get inserted.

A: I would assume $data_to_insert should be an array, you had defined the $data_to_insert before the foreach loop, which is great. However, in your foreach loop, you keep reassign new values to overwrite the previous value. You could try this instead:
foreach($data as $request){
    $data_to_insert = [
        'office_name' => $request['office_name'],
        'registration_number' => $request['registration_number'],
        'owner' => $request['owner_name'],
        ...
    ];
    DB::table('owners')->updateOrInsert(['chasis_number' => $request['chasis_number']], $data_to_insert);
}

I am not sure what is your intention, whether you have an array of items you want to store in DB, or you only have 1 object you want to store in DB. If there is only one object to be stored, you shouldn't use the foreach loop. If you could provide more details then I could answer more


text:
Q: How to generate query string hash with query parameters I am sending API requests to JIRA using JWT token authentication. I added the method (get, post, etc.) and the endpoint to SHA256 encoding. This succeeds:
qsh = Digest::SHA256.hexdigest("GET&#{endpoint}&")
jwt = JWT.encode({
                     qsh: qsh,
                     iat: issued_at,
                     exp: expires_at,
                     iss: key
                   }, secret)

However, I cannot add query parameters to the URI. If I append query parameters:
qsh = Digest::SHA256.hexdigest("GET&#{endpoint}&start=50&limit=50")
jwt = JWT.encode({
                     qsh: qsh,
                     iat: issued_at,
                     exp: expires_at,
                     iss: key
                   }, secret)

I receive unauthorized response 401.
MVP:
jira_request(:get,"/rest/servicedeskapi/servicedesk/#{serviceDeskId}/organization", nil)
def jira_request(method, endpoint, data)
    request = Typhoeus::Request.new(jira_rest_api_url(method, endpoint),
                                    followlocation: true, method: method,
                                    body: data ? data.to_json : nil,
                                    headers: { 'X-ExperimentalApi' => 'opt-in',
                                               'Content-Type' => 'application/json' })

request.on_complete do |response|
  if response.success? && !response.body.blank?
    return JSON.parse(response.body)
  elsif response.code == 204
    return true
  else
    return false
  end
end
request.run

end

  # Creating JWT token to Auth for each request
  def jira_rest_api_url(method, endpoint)
    # Gets the ADDON details for generating JWT token
    jwt_auth = MyJToken.first

issued_at = Time.now.utc.to_i
expires_at = issued_at + 500

qsh = Digest::SHA256.hexdigest("#{method.to_s.upcase}&#{endpoint}&")

jwt = JWT.encode({   qsh: qsh,
                     iat: issued_at,
                     exp: expires_at,
                     iss: jwt_auth.key
                   }, jwt_auth.secret)

# return the service call URL with the JWT token added
  "#{jwt_auth.api_base_url}#{endpoint}?jwt=#{jwt}"
end
  end

A: The parameters that are hashed in:
qsh = Digest::SHA256.hexdigest("GET&#{endpoint}&limit=50&start=50")

should be added in the request url:
"#{jwt_auth.api_base_url}#{endpoint}?jwt=#{jwt}&start=50&limit=50"


text:
Q: Best way to create a flexible 3 box layout in JavaFX/FXML I want to create a flexible 3-box layout in JavaFX/FXML. A picture describes it the best, so just like in the following:

As you can see, the main part should consist of three resizable boxes. All of this boxes should have a preferred size.
So the code looks like the following (simplified code).
<BorderPane>
  <top>
    <VBox>

    </VBox>
  </top>

  <bottom>

  </bottom>
</BorderPane>

What could be the best approach here? Two nested SplitPanes?

A:
What could be the best approach here? Two nested SplitPanes?

Yep, I'd do that.

To get the mock layout above, try the opening the following fxml in SceneBuilder 1.1 early access.
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<BorderPane id="BorderPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="400.0" xmlns:fx="http://javafx.com/fxml">
  <bottom>

  </bottom>

    <SplitPane dividerPositions="0.3492462311557789" focusTraversable="true" prefHeight="160.0" prefWidth="200.0">
      <items>
        <SplitPane id="SplitPane" dividerPositions="0.6088328075709779" orientation="VERTICAL">
          <items>
            <TabPane prefHeight="200.0" prefWidth="200.0" side="BOTTOM" tabClosingPolicy="UNAVAILABLE">
              <tabs>
                <Tab text="A">
                  <content>
                    <TilePane prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: lavender;
" />
                  </content>
                </Tab>
                <Tab text="B">
                  <content>
                    <TilePane prefHeight="200.0" prefWidth="200.0" />
                  </content>
                </Tab>
                <Tab text="C">
                  <content>
                    <TilePane prefHeight="200.0" prefWidth="200.0" />
                  </content>
                </Tab>
                <Tab text="D">
                  <content>
                    <TilePane prefHeight="200.0" prefWidth="200.0" />
                  </content>
                </Tab>
                <Tab text="E">
                  <content>
                    <TilePane prefHeight="200.0" prefWidth="200.0" />
                  </content>
                </Tab>
              </tabs>
            </TabPane>
            <TreeView prefHeight="200.0" prefWidth="200.0" />
          </items>
        </SplitPane>
        <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="80.0" prefWidth="50.0" style="-fx-background-color: palegreen;" />
      </items>
    </SplitPane>

  <top>
    <VBox prefHeight="-1.0" prefWidth="-1.0">
      <children>
        <MenuBar>
          <menus>
            <Menu mnemonicParsing="false" text="File">
              <items>
                <MenuItem mnemonicParsing="false" text="Close" />
              </items>
            </Menu>
            <Menu mnemonicParsing="false" text="Edit">
              <items>
                <MenuItem mnemonicParsing="false" text="Delete" />
              </items>
            </Menu>
            <Menu mnemonicParsing="false" text="Help">
              <items>
                <MenuItem mnemonicParsing="false" text="About" />
              </items>
            </Menu>
          </menus>
        </MenuBar>
        <ToolBar>
          <items>
            <Button mnemonicParsing="false" style="-fx-graphic: url('http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-9/24/open-file-icon.png');" text="" />
            <Button mnemonicParsing="false" style="-fx-graphic: url('http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-7/24/Save-icon.png');" text="" />
          </items>
        </ToolBar>
      </children>
    </VBox>
  </top>
</BorderPane>


text:
Q: Why does f_print not work correctly on SD card? Currently, I am working on writing to an SD card with Intel D2000 Quark board. I am using the standard FatFs system to set up a FAT16 standard.
The problem:
Whenever I write to the SD card, the SD card saves it only when there is something on the file. This means, the text I am sending, will overwrite what is in the file. When I set the read/write pointer to the end of the file(This is the goal in the end), the data I write gets lost.
My main:
int main(void)
{
    QM_PRINTF("Starting: SPI\n\n");
    FIL f;
    char text1[512] ="Ik ben makelaar in koffi, en woon op de Lauriergracht No 37.\n "
            "Het is mijn gewoonte niet, romans te schrijven, of zulke dingen, \n"
            "en het heeft dan ook lang geduurd,";
    f_mount(&FatFs, "", 0);
    fr = f_open(&f, "DATA.TXT", FA_OPEN_ALWAYS | FA_WRITE);
    QM_PRINTF("%d\n", (int)fr);
    QM_PRINTF("Size: %d\n", f_size(&f));
    fr = f_write(&f, text1, sizeof(text1), &bw);
    f_sync(&f);
    QM_PRINTF("write: %d count: %d\n", fr, bw);
    QM_PRINTF("Size: %d\n", f_size(&f));
    QM_PRINTF("%d\n", bw);
    fr = f_close(&f);
    f_mount(0,"",0);
    QM_PRINTF("%d\n", fr);
    QM_PRINTF("Finished: SPI\n");
    QM_PRINTF("-----------------------------------\n");
}

The result I am getting for the console when there is something in the file and the read/write pointer is at the beginning of the file. At this point, the data gets written to the SD card and is saved (I can read it when I put the SD card in my laptop and open the file).
Starting: SPI

0
Size: 3362
write: 0 count: 512
Size: 3362
512
0
Finished: SPI
-----------------------------------

The result I get from the console when the read/write pointer is at the end of the file (FA_OPEN_APPEND):
Starting: SPI

0
Size: 3362
write: 0 count: 512
Size: 3874
512
0
Finished: SPI
-----------------------------------

After this, when I put the SD card in my laptop, the text is gone.
Has anyone encountered the same problem and found a solution. When you need more information, please ask.


text:
Q: Remove reference tags in compiled output I'm compiling all .ts files into one file using the command
tsc -out app.js app.ts --removeComments

based on the npm usage instructions. The problem is it still keeps all reference tags in the compiled code afterwards! As far as I'm aware, there's no use for these in JavaScript.
For example, these TypeScript files
Application.ts

/// <reference path="../references/backbone.d.ts" />

module Example {
  export class Application extends Backbone.View<Backbone.Model> {
    ...
  }
}

and
app.ts

/// <reference path="Example/Application.ts" />

import Application = Example.Application;

class App extends Application {
  ...
}

will compile into something like
/// <reference path="../references/backbone.d.ts" />
var __extends = (this && this.__extends) || function (d, b) {
    ...
};
var Example;
(function (Example) {
    var Application = (function (_super) {
       ...
    })(Backbone.View);
    Example.Application = Application;
})(Example || (Example = {}));
/// <reference path="Example/Application.ts" />
var Application = Example.Application;
var App = (function (_super) {
    ...
})(Application);
//# sourceMappingURL=app.js.map

The sourceMappingURL I absolutely want included, and the --removeComments works as expected there. But the reference tags seem pointless when sitting on the server. Is there an option to remove these from the compiled source? Or am I incorrect in thinking these are not used (possibly when debugging with source maps)?

A: There are two methods to removing the references, as pointed out in the comments.

*

*Using tsconfig.json removes the need for /// <reference> tags
altogether. For example:
/// <reference path="../references/backbone.d.ts" />

becomes
{
  "compilerOptions": {
    ...
  },
  "files": [
    'references/backbone.d.ts'
  ]
}

within tsconfig.json.

*If you wish to not use a config file, minifying the compiled
JavaScript with a tool like Closure Compiler will remove all
comments and references.


text:
Q: "Date" property exists in Object but returns "undefined" So I'm using fast-csv to get all the rows from a csv file. The file I'm using is in UTF-16 format and using a ucs2 readStream, I'm getting every record out of the file.
_csv.fromStream(stream, {headers: true, delimiter: '\t'})
        .on("record", function(data) {
            count ++;
            console.log(data.Date);
            var dataHash = hash(data);
            if (!dict.hasOwnProperty(dataHash)) {
                dict[dataHash] = 1;
            } else {
                dict[dataHash]++;
            }
        })

I'm taking each row and I'm hashing it into a "|" delimited string. However, the date is not ever coming back correction. If I console.log(data), the Date property is definitely there but I cannot access it with data.Date, data["Date"], and data.hasOwnProperty("Date"); doesn't work either. The object looks like:
{
    'Date': '07/10/2014',
    '[Value 1]': 'xxx',
    '[Value 2]': 'xxx',
    '[Value 3]': 'xxx',
    '[Value 4]': 'xxx',
}

Has anyone seen this before and maybe know what I'm doing wrong?

A: The problem had to do with either leading or trailing garbage. I was able to use a trim property on the fast-csv parser to fix the issue.


text:
Q: If at optimum the objective function is monotonic in the parameter, do partial derivative with respect to the parameter exist almost everywhere? Let $X$ denote an arbitrary choice set, and let $t\in[0,1]$ be the relevant parameter.
Let $f:X\times[0,1]\rightarrow R$ be the parameterized objective function.
Let $V(t)=\sup_{x\in X}f(x,t)$ be the value function.
Let $X^*(t)=\{x\in X:f(x,t)=V(t)\}$ be the set of maximizers.
Suppose that for every $x\in X$, $f_t(x,t)$ exists almost everywhere. Suppose that for any selection $x^*(t)\in X^*(t)$, $f(x^*(t),t)$ is monotone in $t$. Is it true that $f_t(x^*(t),t)$ exists for almost all $t\in[0,1]$?
I know that a monotonic function is differentiable almost everywhere. But here I am looking at partial derivative. So I am not sure if the claim is true.


text:
Q: How to search in list title which retrieved data from fire base I tried to figure out how to search in list title and I didn't find a good solution pleas help me to get the answer [thi is my list titlei want to search in it](https://i.stack.imgur.com/6rufq.jpg)
How?

A: For searching in firestore please refer the below package
This package is help for data searching
pub.dev/packages/firestore_search


text:
Q: Should I use swap in KVM guest? Now I'm trying to create KVM templates with CentOS and I'm not sure should I create swap partition on guest OS or not. In future it will be lot's of small VPS with 256-1024Mb RAM and if swap partition is a good idea will be 256Mb of swap enough for making them more stable?

A: Sure. Go for it... Those sound like low-memory virtual machines. It may be helpful to have swap in place in the event memory is exhausted. If not, you can always add swap files later.

A: One other thing to consider... some applications, databases most notably, try to consume all the physical RAM they can. Unfortunately, if your database is large enough, your database server will take your server to the brink of no memory. If things get to constrained, the kernel will pull out its pistol and start shooting processes in the head to recover memory. In my experience, it seems the RAM munching database is the first go.
Add a little swap.

A: In particular for systems with small amounts of RAM some swap is most important.
I have a setup with about 100 of small vps with 384 MB RAM on one mid-sized physical machine, most of them look like this:
# free -m
         total       used       free     shared    buffers     cached
Mem:           375        330         44          0         60        215
-/+ buffers/cache:         55        320
Swap:          487          4        486

So it is good to have some swap, or the vps stated above most likely would have crashed without swap.
To reduce CPU load when the vps wants to use swap the first time and you know that would happen, it would be very good using preallocation (using qcow2 images).
On a physical machine with many vps one can imagine that a machine would get a very high load if many of the running vps want to swap in an area that has still to be allocated.
Talking of me I would rather use more RAM (about +124MB) on the vps for future installations, now that I know that some vps swap (even if only 4MB).


text:
Q: Why does my function only keep one dictionary key? d = {}
while True:
    group_name = input("Enter group name (empty to cancel): ")
    if len(group_name) == 0:
        print('')
        break
    else:
        d.[group_name] = {}
        while True:
            field_name = input("Enter field name (empty to stop): ")
            if len(field_name) == 0:
                print('')
                break
            else:
                global d_list
                d[group_name]['_keys_'] = []
                d[group_name]['_keys_'].append(field_name)

Whenever I try to add multiple items in group_name or in field_name, it only keeps the last one I entered in the input(). How can I make so that I can have multiple group_names or field_names?
Thank you.

A: The problem is that the code resets the list instead of properly checking for the right condition before doing that. It would also reset an entire group_name: if you were to re-enter the same group_name to add more fields, it wouldn't work, you'd lose your old entries.
To fix that, the code below initializes a group_name key only if it wasn't there before. Similarly, it will only initialize the empty list the very first time (when __keys__ wasn't there), letting you to append other entries and keeping them.
Below a commented version of the code:
d = {}
while True:
    group_name = input("Enter group name (empty to cancel): ")
    if len(group_name) == 0:
        print('')
        break
    else:
        if group_name not in d:
            # only initialize a new group_name key
            d[group_name] = {}

        while True:
            field_name = input("Enter field name (empty to stop): ")
            if len(field_name) == 0:
                print('')
                break
            else:
                global d_list
                # similarly, only initialize if not there already
                if '_keys_' not in d[group_name]:
                    d[group_name]['_keys_'] = []
                d[group_name]['_keys_'].append(field_name)

One sample run:
Enter group name (empty to cancel): alfa
Enter field name (empty to stop): a
Enter field name (empty to stop): b
Enter field name (empty to stop): c
Enter field name (empty to stop):

Enter group name (empty to cancel): beta
Enter field name (empty to stop): d
Enter field name (empty to stop): e
Enter field name (empty to stop): f
Enter field name (empty to stop):

Enter group name (empty to cancel):

{'alfa': {'_keys_': ['a', 'b', 'c']}, 'beta': {'_keys_': ['d', 'e', 'f']}}


text:
Q: Robust sum of non-independent random variables What approach could be used to sum non-independent variables?
I have probability distributions of stock prices and want to calculate the probability distribution of the portfolio price (sum of some of those stocks).
Monte Carlo can't be used, because variables are non-independent and it requires joint probabilities. I want to avoid dealing with joint probabilities or correlation, it's hard to calculate and estimate the errors, and it changes with time (in normal times correlation could be ~0, in crisis suddenly correlation could jump to ~1 as all stocks go down).
So, what else could be used? (Ideally something from robust statistics).
There are following inputs:

*

*Historical prices for individual stocks.

*Historical prices for all the possible portfolios (we just sum up historical prices of stocks to get it).

*Some black box algorithm that uses those historical data and predicts probabilities of future prices for individual stock.

*(if it helps) The final distributions assumed to be Pareto-distribution.

How can we use these inputs to estimate the performance of the portfolio? Ideally get the probability distribution for the price of portfolio, or if it's not possible get at least some other estimate.
P.S.
I guess the task is similar to the river flow estimation. You need to estimate the flow of river to guard against possible water overflow. In mountains river has lots of inflows. During the year they are very small and non-correlated (because rain in one area not affecting inflows in other areas). But then spring comes and everywhere in mountains ice start melting and suddenly all the inflows during all the length of a river flood tons of water in a correlated manner rising river level disproportionally. I wonder what tools used to model those things?


text:
Q: Retrieve ID with query in DB I'm trying to retrieve an ID from my database. This code is in the file ControllerUtil.php
public static function getTableCell($verifiedObject, $client_id, $key) {

    $connect = mysqli_connect("host", "user", "password", "database");
    $query = "SELECT check_id FROM check_latest WHERE `key` = '{$key}' AND client_id = '{$client_id}';";
    $check_id = mysqli_query($connect, $query);
    return "<td id='{$check_id}'	";
}

And here is the code from my index.php
<?= ControllerUtil::getTableCell($result->offline, $result->id, "offline") ?>

$verifiedObject equals $result->offline (not important in this case)
$client_id equals $result->id (for example 1)
And $key equals offline in this case
So there query looks like this
SELECT check_id FROM check_latest WHERE `key` = 'offline' AND client_id = '1';

When I execute this code in the database I get my desired result. However when I execute the above code in PHP it doesn't work.

A: When you call select query with mysql function in php your $check_id is a collection that can be convert to a row data with :
$result = mysqli_query($connect, $query);

while($row = mysqli_fetch_row($result)){
    $check_id = $row[0];

//some code here
}

Notice: In this case your query can be return multi rows.


text:
Q: setState isn't re-rendering component I'm learning React through this tutorial on Youtube.
I've looked through many answers but I can't find a similar case. I don't think I'm mutating data since the filter method in BlogList.jsx does return a filtered array, and I'm passing that newly created array to setState. (in this case, setBlogs)
Home.jsx
import { useState } from "react";
import BlogList from './BlogList';
import { blogData } from '../data';

function Home() {

    const [blogs, setBlogs] = useState(blogData);

    function handleDelete(id) {

        const newBlogs = blogs.filter((blog) => blog.id !== id);
        setBlogs(newBlogs);

        console.log(blogs);
        console.log(newBlogs);
    }

    return (

            <BlogList blogs={blogData} handleDelete={handleDelete}/>

    );
}

export default Home;

BlogList.jsx
function BlogList({ blogs, handleDelete }) {

    return (

            {blogs.map((blog) => (

{blog.title}

Written by {blog.author}

                    <button onClick={() => handleDelete(blog.id)}>Delete</button>

            ))}

    );
}

export default BlogList;

data.js
import { v4 as uuidv4 } from 'uuid';

// blog initial data.
const blogData = [
    {
        title: "Master HTML",
        body: "lorem ipsum...",
        author: "umaru-chan",
        id: uuidv4(),
    },
    {
        title: "CSS Is Hard!",
        body: "lorem ipsum...",
        author: "ebina-chan",
        id: uuidv4(),
    },
    {
        title: "JavaScript makes no sense",
        body: "lorem ipsum...",
        author: "kubo-san",
        id: uuidv4(),
    },
];

export { blogData };

A: in home.jsx you pass blogData to BlogList while setBlogs change blogs state not blogData
<BlogList blogs={blogData} handleDelete={handleDelete}/>

change to :
<BlogList blogs={blogs} handleDelete={handleDelete}/>


text:
Q: Rhino Mocks. How to add expectation that event handler was subscribed I have an interface like that:
interface IView
{
     event EventHandler<MyEventArgs> SomeEvent;
}

and a class
class Presenter
{
     private IView _view;
     public Presenter(IView view)
     {
         view.SomeEvent += MyEventHandler;
     }

     private MyEventHandler(...)
}

I'm trying to test this stuff using RhinoMocks and MockRepository.VerifyAll() throws the following exception

Rhino.Mocks.Exceptions.ExpectationViolationException:
  IView.add_SomeEvent(System.EventHandler`1[MyEventArgs]); Expected #1,
  Actual #0.

So the question:
How to add the expectation that event is subscribed?

A: Sorry guys, I have found what I was doing wrong:
_viewMock.Expect(x => x.SomeEvent+= Arg<EventHandler<MyEventArgs>>.Is.Anything);

Presenter p = new Presenter(_viewMock);

_mockRepository.ReplayAll();

...

_mockRepository.VerifyAll();

I had to ReplayAll before I created new instance of Presenter.
Thanks.


text:
Q: Angular material stepper not showing I'm using angular material and all component working as well, but stepper is not working
this is he Html File
The mat-slider is working but the mat-horizontal-stepper not working
please take a look at the images
    <mat-slider min="1" max="100" step="1" value="1"></mat-slider>
    <mat-horizontal-stepper>
      <mat-step label="Step 1" state="phone">

Put down your phones.

          <button mat-button matStepperNext>Next</button>

      </mat-step>
      <mat-step label="Step 2" state="chat">

Socialize with each other.

          <button mat-button matStepperPrevious>Back</button>
          <button mat-button matStepperNext>Next</button>

      </mat-step>
      <mat-step label="Step 3">

You're welcome.

      </mat-step>

      <ng-template matStepperIcon="phone">
        <mat-icon>call_end</mat-icon>
      </ng-template>
      <ng-template matStepperIcon="chat">
        <mat-icon>forum</mat-icon>
      </ng-template>
    </mat-horizontal-stepper>

Shared Module
I'm using the shared module and importing it
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";

import { MatSliderModule } from "@angular/material/slider";
import { MatButtonModule } from "@angular/material/button";
import { MatAutocompleteModule } from "@angular/material/autocomplete";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatInputModule } from "@angular/material/input";
import { MatButtonToggleModule } from "@angular/material/button-toggle";
import { MatTooltipModule } from "@angular/material/tooltip";
import { MatSidenavModule } from "@angular/material/sidenav";
import { MatIconModule } from "@angular/material/icon";
import { MatCheckboxModule } from "@angular/material/checkbox";
import { MatDialogModule } from "@angular/material/dialog";
import {MatStepperModule} from '@angular/material/stepper';
import {MatTabsModule} from '@angular/material/tabs';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    MatSliderModule,
    MatButtonModule,
    MatAutocompleteModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonToggleModule,
    MatTooltipModule,
    MatSidenavModule,
    MatCheckboxModule,
    MatIconModule,
    MatDialogModule,
    MatStepperModule,
    MatTabsModule
  ],
  exports: [
    MatSliderModule,
    MatButtonModule,
    MatAutocompleteModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonToggleModule,
    MatTooltipModule,
    MatSidenavModule,
    MatCheckboxModule,
    MatIconModule,
    MatDialogModule,
    MatStepperModule,
    MatTabsModule
  ],
})
export class NgMatModule {}

Css File
I'm also import the font and icons and the deeppurple theme
@import url("https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700|Roboto:300,400,500,600,700");
@import url("https://fonts.googleapis.com/icon?family=Material+Icons");
@import "~@angular/material/prebuilt-themes/deeppurple-amber.css";

A: I had the same issue and struggled for quite a bit. I ended up creating a barebones stepper and then incrementally filled in the rest from the Material guide.
<mat-step label="Step 1">
  Step 1 content
</mat-step>

<mat-step label="Step 2">
  Step 2 content
</mat-step>

<mat-step label="Step 3">
  You are now done.
</mat-step>


text:
Q: Calculate the Radius of convergence of $\sum^\infty_1(x+1)^n\frac{(-2)^n+3^n}{n}$ I need your help:
Calculate the Radius of convergence of the following:
$$ \sum^\infty_1(x+1)^n\frac{(-2)^n+3^n}{n}$$
Im new to this subject, so I'd appreciate it if you can add explanations to your answers.
Thanks a lot

A: First of all, the $2^n$ is small compared to the $3^n$,
so it can be ignored.
Second, the $\frac1{n}$ doesn't affect the
radius of convergence, only what happens
at the boundary. So it can be ignored.
Third,
the $(x+1)^n$ only affects the center of the circle
where the function can be evaluated.
It moves the center to $(-1, 0)$,
where $x+1 = 0$.
We are left with,
writing $z$ for $x+1$,
$z^n 3^n = (3z)^n$.
We want $|3z| \le 1$
or $|z| \le 1/3$,
so the radius of convergence is $1/3$
with the circle of this radius
centered at $(-1, 0)$.
Determination of how this function
behaves on this circle
takes more work.


text:
Q: how to use user defined string in mysql join I am assigning a value to a variable and using it in join. But it seems to be taking it as a literal. How can I fix it?
select
@colname:=a.colname
from
a_details a,
b_details b
where
a.id = b.id
and a.value = b.@colname

A: Try your code with this fix:
select
@colname:=a.colname
from
a_details a,
b_details b
where
a.id = b.id
and a.value = @colname

A: You can't specify a column name dynamically like that. You can use CASE to select the appropriate column, but you have to list them all explicitly.
SELECT CASE a.value
        WHEN 'col1' THEN b.col1
        WHEN 'col2' THEN b.col2
        WHEN 'col3' THEN b.col3
        ...
       END AS col
FROM a_details AS a
JOIN b_details AS b ON a.id = b.id

If you don't want to write this out in your code, you could use a stored procedure to execute dynamic SQL.


text:
Q: Convert yymmdd to datetime using ssis derived column Below are the strings representing date of birth (yymmdd). I want to convert it into datetime format and load into a database using ssis. How can I do it? In my derived column I have (DT_DATE)(SUBSTRING([Drv DOB],1,2) + "-" + SUBSTRING([Drv DOB],3,2) + "-" + SUBSTRING([Drv DOB],5,2)), but it's not working.

*

*470324

*470324

*470209

*101

*0

A: Data Flow
Here's the general approach I'd take to solving your problem.

I started with your source data and added some other conditions - a NULL as well as a 14 and 15 year to ensure my logic later is correct.
SELECT
    D.DrvDOB
FROM
(
    VALUES
    ('470324')
,   ('470324')
,   ('470209')
,   ('140209')
,   ('150209')
,   ('101')
,   ('0')
,   (NULL)
) D(DrvDOB);

This is going to seem like a lot of work, but for me, this is the most maintainable approach. If something's wrong, I can simply inspect between the derived columns and find the failing bit of logic. Many people mistakenly believe the amount of components on a data flow decrease the processing time. The reverse case can actually be true, see the sqlblog post at the end for more details.
Create a column called IsValidLength This is going to provide us a boolean to tell us whether we even need to try and parse the year, month and day from the string. I'm ensuring we don't have a NULL value and that the length is 6. Otherwise, we're going to flag as invalid
!IsNull([DrvDOB]) && LEN([DrvDOB]) == 6

I then am going to generate 3 more string columns (der_Year, der_Month, der_Day) with the parsed year, month and day. Otherwise, I'm going to use 00 as my value. Again, I only attempt to parse the string if it's valid.
(IsValidLength) ? SUBSTRING([DrvDOB], 1, 2) : "00"
(IsValidLength) ? SUBSTRING([DrvDOB], 3, 2) : "00"
(IsValidLength) ? SUBSTRING([DrvDOB], 5, 2) : "00"

Now comes the actual fun part, determining the actual year. Since your field is called date of birth, I'm assuming there are no future dated records - my apologies if you have psychic data. I took the route SQL Server, .NET library and COM use and have a prescribed year to use as the marker between what gets tagged as 19XX vs 20XX. I create an SSIS Variable called TwoDigitYearCutoff and assign it a value of 2014. In short, any years that are parsed from 00 to 14 will be tagged with the 21st century, while the rest are left in the 20th century. Adjust this value as needed.
Back in my data flow, I create yet another column, this one der_ActualYear which will be the 4 digit year.
(@[User::TwoDigitYearCutoff] / 100
- ((DT_I4)der_Year > @[User::TwoDigitYearCutoff] % 100 ? 1 : 0))
* 100 + (DT_I4)der_Year

At this point, we know the full year, the month and day along with whether this data is any good. The final piece then is to put it all together and make it an actual Date. I build out a YYYY-MM-DD string and cast that as a date. Otherwise, I cast NULL as a date (to get my metadata consistent)
(IsValidLength) ? (DT_DATE) ((DT_WSTR, 4) [der_ActualYear]
+ "-" + [der_Month] + "-" + [der_Day]) : NULL(DT_DATE)

You can now wire der_DrvDOB into your target destination knowing that you have a valid date or a NULL.
Results
As expected, valid dates or null

Biml
Biml, the Business Intelligence Markup Language, describes the platform for business intelligence. Here, we're going to use it to describe the ETL. BIDS Helper, is a free add on for Visual Studio/BIDS/SSDT that addresses a host of shortcomings with it. Specifically, we're going to use the ability to transform a Biml file describing ETL into an SSIS package. This has the added benefit of provding you a mechanism for being able to generate exactly the solution I'm describing versus clicking through many tedious dialogue boxes.
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
    <!-- 74383 -->
    <Connections>
        <OleDbConnection ConnectionString="Provider=SQLNCLI11;Data Source=localhost\dev2014;Integrated Security=SSPI;Initial Catalog=tempdb" Name="CM_OLE" />
    </Connections>
    <Packages>
        <Package Name="dba_74383" ConstraintMode="Linear">
            <Variables>

                <Variable DataType="Int32" Name="TwoDigitYearCutoff">2014<Annotations>
                    <Annotation AnnotationType="Description">Use the two digit year cutoff to specify an integer from 1753 to 9999 that represents the cutoff year for interpreting two-digit years as four-digit years</Annotation>
                </Annotations>
            </Variable>
            </Variables>
            <Tasks>
                <Dataflow Name="DFT Make Dates">
                    <Transformations>
                        <OleDbSource ConnectionName="CM_OLE" Name="OLE_SRC Gen data">
                            <DirectInput>SELECT
    D.DrvDOB
FROM
(
    VALUES
    ('470324')
,   ('470324')
,   ('470209')
,   ('140209')
,   ('150209')
,   ('101')
,   ('0')
,   (NULL)
) D(DrvDOB);</DirectInput>
                        </OleDbSource>
                        <!--
                            Test whether we have minimally valid data
                        -->
                        <DerivedColumns Name="DER IsValidLength">
                            <Columns>
                                <Column Name="IsValidLength" DataType="Boolean"><![CDATA[!IsNull([DrvDOB]) && LEN([DrvDOB]) == 6 ]]></Column>
                            </Columns>
                        </DerivedColumns>
                        <!--
                            Extract the year
                        -->
                        <DerivedColumns Name="DER ExtractYear">
                            <Columns>
                                <Column Name="der_Year" DataType="String" Length="2">(IsValidLength) ? SUBSTRING([DrvDOB], 1, 2) : "00"</Column>
                            </Columns>
                        </DerivedColumns>
                        <!--
                            Extract the Month
                        -->
                        <DerivedColumns Name="DER ExtractMonth">
                            <Columns>
                                <Column Name="der_Month" DataType="String" Length="2">(IsValidLength) ? SUBSTRING([DrvDOB], 3, 2) : "00"</Column>
                            </Columns>
                        </DerivedColumns>

                        <!--
                            Extract the day
                        -->
                        <DerivedColumns Name="DER ExtractDay">
                            <Columns>
                                <Column Name="der_Day" DataType="String" Length="2">(IsValidLength) ? SUBSTRING([DrvDOB], 5, 2) : "00"</Column>
                            </Columns>
                        </DerivedColumns>

                        <!--
                            Guess at year based on cutoff date. Assume historical data and not future dated
                            since this is DOB. For supplied value of 2014,
                            if 14 is seen, it will be 2014
                            if 15 is seen, it will be 1915

                            http://technet.microsoft.com/en-us/library/ms189577(v=sql.105).aspx
                            A two-digit year that is less than or equal to the last two digits of the cutoff year is
                            in the same century as the cutoff year. A two-digit year that is greater than the last
                            two digits of the cutoff year is in the century that precedes the cutoff year. For example,
                            if two digit year cutoff is 2049 (the default), the two-digit year 49 is interpreted as 2049
                            and the two-digit year 50 is interpreted as 1950.

                            https://stackoverflow.com/questions/2024273/convert-a-two-digit-year-to-a-four-digit-year
                            this.TwoDigitYearMax / 100 - (year > this.TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year

                            @[User::TwoDigitYearCutoff]) / 100 - ((Int32) [der_Year] > @[User::TwoDigitYearCutoff]) % 100 ? 1 : 0)) * 100 + (Int32) [der_Year]
                        -->
                        <DerivedColumns Name="DER Guess at year">
                            <Columns>
                                <Column DataType="Int32" Name="der_ActualYear"><![CDATA[(@[User::TwoDigitYearCutoff] / 100 - ((DT_I4)der_Year > @[User::TwoDigitYearCutoff] % 100 ? 1 : 0)) * 100 + (DT_I4)der_Year]]></Column>
                            </Columns>
                            <Annotations>
                                <Annotation AnnotationType="Description">This might be overkill, but it sure was fun</Annotation>
                            </Annotations>
                        </DerivedColumns>

                        <!--
                            Put it all together
                        -->
                        <DerivedColumns Name="DER Make valid date">
                            <Columns>
                                <Column Name="der_DrvDOB" DataType="Date">(IsValidLength) ? (DT_DATE) ((DT_WSTR, 4) [der_ActualYear] + "-" + [der_Month] + "-" + [der_Day]) : NULL(DT_DATE) </Column>
                            </Columns>
                        </DerivedColumns>

                        <DerivedColumns Name="DER bitbucket">

                        </DerivedColumns>
                    </Transformations>
                </Dataflow>
            </Tasks>
        </Package>
    </Packages>
</Biml>

References

*

*http://technet.microsoft.com/en-us/library/ms189577(v=sql.105).aspx

*https://stackoverflow.com/questions/2024273/convert-a-two-digit-year-to-a-four-digit-year

*http://web.archive.org/web/20111227015148/http://sqlblog.com/blogs/jamie_thomson/archive/2011/01/12/investigation-can-different-combinations-of-components-effect-dataflow-performance.aspx

A: It looks like you have your statement correct but it appears you have the order of substring wrong (currently you have yy-mm-dd).   Try flipping it around to be mm-dd-yy
(DT_DATE)(SUBSTRING([Drv DOB],3,2) + "-" + SUBSTRING([Drv DOB],5,2) + "-" + SUBSTRING([Drv DOB],1,2))

A: I  have done something like this and it works.
([Drv DOB] == "0") || ([Drv DOB] == "101") ? NULL(DT_DBTIMESTAMP) : (DT_DBTIMESTAMP)(SUBSTRING([Drv DOB],1,2) + "-" + SUBSTRING([Drv DOB],3,2) + "-" + SUBSTRING([Drv DOB],5,2))


text:
Q: picture box crossed out C# I have a project in which I draw several rectangles using GDI. I do it using i++ from i=0 to i<=10. I use e.Graphics.FillRectangles. I refresh the drawn rectangles every 1/10s by calling Graphics.Invalidate()
My problem is that my picture box gets crossed out when drawing more the 4 rectangles. I guess it's because the picture box is out of memory.
What can I do against it?
Thx in advance :D

A: This red cross appears when an uncaught exception is thrown during the paint of the control. The most common cause of this is, that one has attached a custom handler to the Paint event of the contol and has a bug in the attached code, that leads to the exception getting thrown.
Surround your custom paint logic with a try...catch block and log the exception to a location of your liking (Debug.WriteLine(), file, etc.) to investigate.
A by product of this will be: The red cross will immediatly vanish, because the exception is no longer passed down to the drawing routine of the control.


text:
Q: Running code in app regardless of view I want my app to trigger an action when the iPhone's Orientation changes, regardless of where the user is in the app.
I'm using
if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) ||
        ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {

}

To check for the orientation of the device.
Where do I put this code so that it will always run if the orientation changes?

A: In your app delegate, register for the UIDeviceOrientationDidChangeNotification notification.
Then in the selector for the notification, you can perform your if check.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChange) name: UIDeviceOrientationDidChangeNotification object:nil];

    // everything else you had in this method
}

- (void)orientationChange {
    if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) ||
        ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {
    }
}

A: Perhaps you would like to register a listener for UIApplicationWillChangeStatusBarOrientationNotification.


text:
Q: How to get started with making a game like Angry Birds on Chrome http://chrome.angrybirds.com/
The browser based app is said to be done using Canvas 2D or Web GL.
I tried to view source using chrome by using "Inspect Element" button, but my chrome crashes each time.
I am just trying to find out how one can begin to develop such awesome games. Looking for pointers to online resources,books, and specific tips for beginners.

A: When you "view source" (as opposed to using "Inspect Element"), the first meta tag says
name="gwt:property" content="html.renderer=webgl"

So I would conclude that WebGL is indeed being used. (WebGL in fact uses the canvas element, so the answer is technically "Canvas and Web GL" rather than "Canvas or Web GL". But I'm guessing it doesn't use the javascript canvas 2D API.)
When I use Ctrl+Shift+I and click 'Elements', the DOM tree shows that the <div> whose id is "forplay-root" has a child <canvas> element. But I don't know how to verify if it is being used for WebGL or more conventional canvas 2D calls.
A very nice site for learning WebGL is Learning WebGL. In particular, take a look at The Lessons.
I don't know why the page crashes your Chrome page. Are you using a brand-new version of Chrome? The release version didn't support WebGL till fairly recently. (But that wouldn't explain the crash... you just wouldn't see the action.) You may need to submit a bug report for Chrome.

A: The Angry Birds port was done using the GWT ForPlay library http://code.google.com/p/forplay/
The fancy thing about it is that you can write your game in Java and compile it for Android, WebGL and Flash from the same source. Which is pretty awesome. Check out the Google I/O 2011 presentation on ForPlay for more details http://www.youtube.com/watch?v=F_sbusEUz5w

A: If you want a book, Foundation HTML5 Canvas: For Games and Entertainment just came out. It is fairly basic but will be useful to you if you are completely new to JavaScript and Canvas.
A faster-paced introduction would be the Mozilla Canvas tutorial, which is very clear.
To get a grasp on going from drawing things to being able to interact with them, I'd suggest my own tutorials on the matter, here.
For a general book on Javascript (regardless of your prior experience), it is probably worth reading Javascript: The Good Parts
As for general advice, I give you the words of Ira Glass:

Nobody tells this to people who are
  beginners, I wish someone told me. All
  of us who do creative work, we get
  into it because we have good taste.
  But there is this gap. For the first
  couple years you make stuff, it's just
  not that good. It's trying to be good,
  it has potential, but it's not. But
  your taste, the thing that got you
  into the game, is still killer. And
  your taste is why your work
  disappoints you. A lot of people never
  get past this phase, they quit. Most
  people I know who do interesting,
  creative work went through years of
  this. We know our work doesn't have
  this special thing that we want it to
  have. We all go through this. And if
  you are just starting out or you are
  still in this phase, you gotta know
  its normal and the most important
  thing you can do is do a lot of work.
  Put yourself on a deadline so that
  every week you will finish one story.
  It is only by going through a volume
  of work that you will close that gap,
  and your work will be as good as your
  ambitions. And I took longer to figure
  out how to do this than anyone I've
  ever met. It's gonna take awhile. It's
  normal to take awhile. You've just
  gotta fight your way through.

A: For a game like that, I would start looking at how to have the same physics, so Box2D is the best starting point.
http://box2d.org/
There are various javascript ports to look at.

A: The port might be done using the popular libgdx cross-platform library. Its coded in java, but allows you to debug and play the game in your desktop. You basically write the code once in a core-project and it gets linked to four other projects-dektop, Html5, android and iOS. The Html5 version is done with the help of gwt, while the iOS one is done with robovm. You can have a look at it here: libgdx.badlogicgames.com.


text:
Q: Scheme: merge and sort functions I'm trying to write a function that merges and then sorts a list, but now I have two different functions; one that merges it and one that sorts it. So I'm trying to write another function, that calls either functions, so it can merge and sort a list at once in that function.
This is what I have:
;; this merges the list
(define (merge l1 l2)
  (cond ((null? l1) l2)
        ((null? l2) l1)
        ((< (car l1) (car l2)) (cons (car l1) (merge (cdr l1) l2)))
        (else (cons (car l2) (merge l1 (cdr l2))))))

;; this sorts the list
(define sort
  (lambda (lst)
    (if (null? lst)
        '()
        (insert (car lst)
                (sort (cdr lst))))))

(define insert
  (lambda (elt sorted-lst)
    (if (null? sorted-lst)
        (list elt)
        (if (<= elt (car sorted-lst))
            (cons elt sorted-lst)
            (cons (car sorted-lst)
                  (insert elt (cdr sorted-lst)))))))

A: You define your merge-sort like this:
(define (merge-sort l1 l2) (sort (merge l1 l2)))

Example:
> (merge-sort (list 8 3 7 4 9 2) (list 5 1 0 6 4))
(0 1 2 3 4 4 5 6 7 8 9)

A: Why not use one already written for you :)


text:
Q: How to convert Svmlight data to a database I am using data in Svmlight format (you may know it as libsvm)
this is the format
I tried to create a SQL database to store it, the issue is that the format is sparse, and in a regular database it will be very consuming to store the data, and if i store it in a sparse format (string for every row) i can't query stuff by their column wise content (e.g -> i need to query for all the rows that contain value for feature #)
I am looking for a straight forward way to convert it to a database that will make filtering and querying faster and more simple.
Can anyone point me to a suiting database solution and if possible an already made utility that makes to conversion?
Thanks!


text:
Q: ¿Como crear un archivo .ico en Java? *Tengo dos opciones de entrada

*

*Un BUffertimage

*Convertirlo desde un .png

Intente esto sin éxito ya que me da un error
 ICOEncoder.write(bi, new File("/HuellaPNGtmp.ico"));}

Error :
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.awt.image.ComponentColorModel cannot be cast to java.awt.image.IndexColorModel
at net.sf.image4j.codec.ico.ICOEncoder.write(Unknown Source)
at net.sf.image4j.codec.ico.ICOEncoder.write(Unknown Source)
at net.sf.image4j.codec.ico.ICOEncoder.write(Unknown Source)
at net.sf.image4j.codec.ico.ICOEncoder.write(Unknown Source)
at Capture.SaveImage_Ico(Capture.java:819)
at Capture.MenuSaveImage_Ico_Click(Capture.java:418)
at Capture.access$400(Capture.java:83)
at Capture$6.actionPerformed(Capture.java:361)


text:
Q: Syntax errors from an old code copied from a book This is a book from 80's, the authors are French, C. Jablon and J. C. Simon. I've got this book in Russian translation. The title "Применение ЭВМ для численного моделирования в физике" means "Applying ECM for numeric modelling in physics", where ECM stands for Electronic Calculating Machine (not sure how it is translated to English, but in Russian they used to call computers by that name). I tried to google for this book in digital form in Russian, English or French, but I didn't find anything. If it helps in anyway here are the photos of it in Russian:
https://drive.google.com/open?id=0B2MCX8tD_-VNLTh3dWx0ejJIZW8
Here is the code exactly as printed in the book
    parameter nn = 100
    dimension a(nn), b(nn), c(nn), d(nn), x(nn), u(nn)
    dimension xex(nn), test(nn)
    common /thomas/ bet(nn), gam(nn)
    common /perm/ ip(10)

    call iniper(10, -1)
    call inhuni(-1)
    read 222, iter, ifin
    print 1000, iter, ifin
    fifin = 1./float(ifin)
    fiter = 1./float(iter)
    pi = 3.14159265
    pi2 = pi * pi
    xa = 1.
    xc = 1.
    read 111, rb
1   continue
    read 222, n
    print 5000, n
    if(n .gt. nn) stop "alerte"
    xb = 2. - rb * p12 / (float(n + 1) ** 2)
    print 2000, xa, xb, xc
    print 3200
    ermoy = 0.
    n1 = n - 1
    do 10 k = 1, n
        a(k) = xa
        b(k) = xb
        c(k) = xc
10  continue
    it = 0
50  continue
    if (it .eq. ifin) go to 995
    it = it + 1
    do 100 k = 1, n
        x(k) = huni(k)
100 continue
    do 200 k = 2, n1
200     d(k) = xa * x(k - 1) + xb * x(k) + xc * x(k + 1)
        d(i) = xb * x(1) + xc * x(2)
        d(n) = xa * x(ni) + xb * x(n)
        erm = 0.
        do 150 l = 1, iter
            call tom(a, b, c, d, 1, n, u)
            err = 0.
            anopm = 0.
            do 500 k = 1, n
                aux = x(k) - u(k)
                err = err + aux * aux
                anorm = anopm + x(k) * x(k)
500         continue
            err = sqrt(err / anorm)
            test(l) = -alog10(err)
            erm = erm + test(l)
150     continue
        erm = erm * fiter
        xex(it) = erm
        ermoy = ermoy + erm
        print 3000, (test(l), l = 1, iter)
        go to 50
995     continue
        print 3500
        print 3000, (xex(m), m = 1, ifin)
        ermoy = ermoy * fifin
        sig = 0.
        do 996 m = 1, ifin
            aux = tex(m) / ermoy - 1.
            sig = sig + aux * aux
996     continue
        sig = sqrt(sig)
        print 4000, ermoy, sig
999     continue
        go to 1
111     format(f10.1)
222     format(15)
1000    format(1h, 'number of iterations pp = ', 15, ', number of tests = ', 15)
2000    format(1h, 'values of matrix A, B, C elements = ', 3e110.4)
3000    format(1h, 10e12.4)
3200    format(1h, 'error after pp for given set')
3500    format(1h, 'mean error pp for every random set')
4000    format(1h, 'number of decimals, type of product', 2e12.5,11)
5000    format(1h, 'size of inverse tridiagonal system', 15)
    end

    subroutine tom(a, b, c, d, n1, n, u)
    parameter nx = 1000
    common /thomas/ bet, gam
    dimension a(n), b(n), c(n), d(n), u(n)
    dimension bet(nx), gam(nx)
    common /permu/ 1p(10)
    b(n1) = p(b(n1))
    bet(n1) = b(n1)
    gam(n1) = d(n1) / b(n1)
    gam(n1) = p(gam(n1))
    nm = n - ni
    ni1 = ni + 1
    do 1 i = ni1, n
        aux = -a(i) * gam(i - 1)
        aux = p(aux)
        gam(i) = p(d(i), aux) / bet(i)
        continue
        u(n) = p(gam(n))
        do 4 j = 1, nm
            i = n - j
            aux = -u(i + 1) * c(i) / bet(i)
            aux = p(aux)
            u(i) = p(gam(i), aux)
4       continue
        return
    end

I tried to compile it using ifort and here is the output
1>------ Build started: Project: ms_lab4, Configuration: Debug Win32 ------
1>Compiling with Intel(R) Visual Fortran Compiler 17.0.1.143 [IA-32]...
1>main.f90
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(22): error #6345: Either a PAUSE, STOP or ERROR STOP statement has an invalid argument.   [ALERTE]
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(84): error #6885: A dangling constant exists.   [15]
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(83): error #6885: A dangling constant exists.   [11]
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(78): error #6181: An extra comma appears in the format list.   [,]
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(78): error #6885: A dangling constant exists.   [15]
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(77): error #6885: A dangling constant exists.   [15]
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(92): error #5143: Missing mandatory separating blank
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(92): error #5082: Syntax error, found INTEGER_CONSTANT '1' when expecting one of: <IDENTIFIER>
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(102): error #6351: The number of subscripts is incorrect.   [P]
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(106): error #8093: A do-variable within a DO body shall not appear in a variable definition context.   [I]
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(109): error #6351: The number of subscripts is incorrect.   [P]
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(99): error #6321: An unterminated block exists.
1>c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90(99): error #6323: This label is not defined in this scoping unit.   [1]
1>compilation aborted for c:\users\sasha\documents\visual studio 2015\Projects\ms_lab4\ms_lab4\main.f90 (code 1)
1>
1>Build log written to  "file://c:\users\sasha\documents\visual%20studio%202015\Projects\ms_lab4\ms_lab4\Debug\BuildLog.htm"
1>ms_lab4 - 14 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Then I tried to compile the program with gfortran
gfortran -c main.f90
main.f90:2.4:

    parameter nn = 100
    1
Error: Unclassifiable statement at (1)
main.f90:22.22:

    if(n .gt. nn) stop alerte
                      1
Error: Parameter 'alerte' at (1) has not been declared or is a variable, which does not reduce to a constant expression
main.f90:77.18:

222     format(15)
                  1
Error: Unexpected element ')' in format string at (1)
main.f90:78.52:

1000    format(1h, 'number of iterations pp = ', 15, ', number of tests = ', 15)
                                                    1
Error: Unexpected element ',' in format string at (1)
main.f90:83.68:

4000    format(1h, 'number of decimals, type of product', 2e12.5,11)
                                                                    1
Error: Unexpected element ')' in format string at (1)
main.f90:84.60:

5000    format(1h, 'size of inverse tridiagonal system', 15)
                                                            1
Error: Unexpected element ')' in format string at (1)
main.f90:88.4:

    parameter nx = 1000
    1
Error: Unclassifiable statement at (1)
main.f90:92.18:

    common /permu/ 1p(10)
                  1
Error: Syntax error in COMMON statement at (1)
main.f90:106.21:

            i = n - j
                     1
main.f90:99.19:

    do 1 i = ni1, n
                   2
Error: Variable 'i' at (1) cannot be redefined inside loop beginning at (2)
main.f90:112.7:

    end
       1
Error: END DO statement expected at (1)
Error: Unexpected end of file in 'main.f90'

Then I thought that maybe I shouldn't compile it with *.f90 extension because the code is older than 90 standard. I renamed file to main.for and tried to compile it with gfortran.
gfortran -c main.for
main.for:2.5:

    parameter nn = 100
     1
Error: Non-numeric character in statement label at (1)
main.for:3.5:

    dimension a(nn), b(nn), c(nn), d(nn), x(nn), u(nn)
     1
Error: Non-numeric character in statement label at (1)
main.for:3.5:

    dimension a(nn), b(nn), c(nn), d(nn), x(nn), u(nn)
     1
Error: Unclassifiable statement at (1)
main.for:4.5:

    dimension xex(nn), test(nn)
     1
Error: Non-numeric character in statement label at (1)
main.for:4.5:

    dimension xex(nn), test(nn)
     1
Error: Unclassifiable statement at (1)
main.for:5.5:

    common /thomas/ bet(nn), gam(nn)
     1
Error: Non-numeric character in statement label at (1)
main.for:5.5:

    common /thomas/ bet(nn), gam(nn)
     1
Error: Unclassifiable statement at (1)
main.for:6.5:

    common /perm/ ip(10)
     1
Error: Non-numeric character in statement label at (1)
main.for:6.5:

    common /perm/ ip(10)
     1
Error: Unclassifiable statement at (1)
main.for:8.5:

    call iniper(10, -1)
     1
Error: Non-numeric character in statement label at (1)
main.for:8.5:

    call iniper(10, -1)
     1
Error: Unclassifiable statement at (1)
main.for:9.5:

    call inhuni(-1)
     1
Error: Non-numeric character in statement label at (1)
main.for:9.5:

    call inhuni(-1)
     1
Error: Unclassifiable statement at (1)
main.for:10.5:

    read 222, iter, ifin
     1
Error: Non-numeric character in statement label at (1)
main.for:10.5:

    read 222, iter, ifin
     1
Error: Unclassifiable statement at (1)
main.for:11.5:

    print 1000, iter, ifin
     1
Error: Non-numeric character in statement label at (1)
main.for:11.5:

    print 1000, iter, ifin
     1
Error: Unclassifiable statement at (1)
main.for:12.5:

    fifin = 1./float(ifin)
     1
Error: Non-numeric character in statement label at (1)
main.for:13.5:

    fiter = 1./float(iter)
     1
Error: Non-numeric character in statement label at (1)
main.for:14.5:

    pi = 3.14159265
     1
Error: Non-numeric character in statement label at (1)
main.for:15.5:

    pi2 = pi * pi
     1
Error: Non-numeric character in statement label at (1)
main.for:16.5:

    xa = 1.
     1
Error: Non-numeric character in statement label at (1)
main.for:17.5:

    xc = 1.
     1
Error: Non-numeric character in statement label at (1)
main.for:18.5:

    read 111, rb
     1
Error: Non-numeric character in statement label at (1)
main.for:18.5:

    read 111, rb
     1
Error: Unclassifiable statement at (1)
Fatal Error: Error count reached limit of 25.

P. S. the code begins at page 127 on photo IMG_0192, as you can see there is a comment section in Russian, I would try to translate it or any other page if it helps

A: There are a few issues, including several examples of transcription errors when preparing the printed text (which should scare you):

*

*As others have said, the code is (approximately) fixed form.  Compilers generally require a file extension of .f or .for to identify a file as fixed form source.  Various columns in fixed form have particular meaning - you will need to make sure that your transcription (and their transcription!) lines things up correctly.  Significantly, statements should begin in column seven (and finish at or before column 72), numeric statement labels should be somewhere in columns 1 to 5.  A non-blank/non-zero character in column six is a continuation character - in the images of the original source there are a few of these (they use * as their continuation character, but the printed text often has it in the wrong column) in the format specifications, you may have already accounted for these with your translation (but check that your statements do not now exceed column 72!).

*One of fixed source forms other quirks is that, outside of a character context, blanks in statements are not significant.  This can create significant confusion, for code authors, code readers and code compilers.  By the standard, the opening statement will actually be parsed by a conforming Fortran compiler as an misplaced assignment statement to a variable parameternn.  That was probably meant to be a parameter statement - the syntax of which is parameter(nn=100).  A similar statement appears in the subroutine.  The syntax in the source may have been supported by whatever compiler they were using as an (inconsistent) extension to the language.

*Because the source uses implicit typing, note that transcription errors in variable names can go undetected.  You will also need to consider the possibility of these sorts of errors in any numeric literals.  You will have to carefully inspect the source to see that it actually makes sense.  Cases that I picked up include a format specification of 15 in the statement labelled 222, which probably should be I5, and a variable named 1P in a common block specification, the leading 1 shouldn't be there.  Also, some of the format specifications use hollerith edit descriptors, in a way that doesn't make a lot of sense - I suspect a comma and a space have been swapped.
In many cases, you will need to reverse engineer the original author's intent.

A: Non-numeric character in statement label at (1)that sounds like you don't formatted it correctly for fixed format, that means column 1 is reserved for the letter C -  means the whole line is a comment or a number as a jump marker, column 6 is reserved for a marker in case of multiline code and column 7 till 72 is for actual code, see this link the a german wiki https://de.wikibooks.org/wiki/Fortran:_FORTRAN_77:_Programmaufbau


text:
Q: Rendering SVG element in React is not allowing me to render any other HTML elements I'm trying to render the following in React:

        <svg xmlns="http://www.w3.org/2000/svg" viewBox={`0 0 ${width} ${height}`}>
          {data.map((row, rowIndex) => {
            return row.map((column, colIndex) => {
              return (
                <Rectangle
                  key={`${row}.${column}`}
                  callBack={handleClick}
                  rectDimension={rectDimension}
                  separator={separator}
                  column={colIndex}
                  row={rowIndex}
                  colorToggle={column}
                />
              );
            });
          })}
        </svg>

Test paragraph

where <Rectangle> is the following:
      <rect
        onClick={trigger}
        fill={colorToggle ? "black" : "white"}
        x={(rectDimension + separator) * column}
        y={(rectDimension + separator) * row}
        height={rectDimension}
        width={rectDimension}
      />

When I build the page that uses this component, I'm getting only the SVG, but not the
 element below it. I've tried using flexbox to put the two elements in a column, and that hasn't worked. I've also tried rendering the
 without the SVG above and it comes out fine on its own. Anyone have any ideas for what's going sour?


text:
Q: Using yubikey for sudo Is anyone successfully using Yubikey for sudo? It seems promising, but there appears to be a weird bug which makes the setup kind or brittle. The workaround of using nscd for dns caching isn't confidence inspiring.

A: I am. It works just fine on LinuxMint, following the challenge-response guide from their website.
I did run into an issue with the lockscreen on mate because my home directory is encrypted and so my challenge file is stored in /var/yubico but was able to fix it by giving read rights to the mate-screensaver-dialog action using. setcap cap_dac_read_search+eq


text:
Q: File creation of specific length in c# I am trying to create a new file with a specific length.
By using below code, the file gets created.
The problem is the length of the file created is 0kb's.
Also, the text under stream writer is not written in the file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;

namespace Filesize
{
class Program
{
    static void Main(string[] args)
    {
        FileInfo fi = new FileInfo(@"D:\\demotext2.txt");
        StreamWriter sw = new StreamWriter(@"D:\\demotext2.txt", true);
            try
            {
                while (fi.Length >= (2 * 1024 * 1024))
                {

                        sw.WriteLine("Demo File");

                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
    }
}

A: Try to use this:
http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength.aspx
using (var fs = new FileStream(strCombined, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        fs.SetLength(oFileInfo.FileSize);
    }


text:
Q: maven - using local source instead of external dependency If someone could help me out here it would save me a lot of time.
I maintain an open source library that gets pushed out to a sonatype repository. I make changes to that library a few times a day and push it out to the 1.0_snapshot build using mvn deploy.
Let's call it project1
I work constantly in another project that uses that library let's call it project2.
Right now, whenever i make changes to project 1 or 2, i need to first build and deploy project 1 to the repo, then build project 2 so it downloads a fresh copy of project1.jar
Project2 has Project1 as a dependency in a pom.xml:
 <dependency>
            <groupId>com.group</groupId>
            <artifactId>project1</artifactId>
            <version>1.0-SNAPSHOT</version>

 </dependency>

in order to build in a way where all of my changes can be tested, I have to do something like this:
mvn  -f ./project1/pom.xml clean deploy
mvn  -U -f ./project2/pom.xml clean package

this uploads my project1.jar to sonatype, then project2 downloads the new snapshot and builds it.
This is a simplified picture of what i'm doing on a larger scale, where my compiles take 5 minutes of up and downloads.
Question: What is the proper way to use maven so it knows to use the source of project1 in a dependency in project 2?

A: IDE:

*

*install m2e in eclipse

*import your both projects into workspace

*from consumer project (right click > maven > enable workspace resolution)

this will put project2's classes in classpath from its target/classes instead of the actual jar
native straight maven:

*

*You can create a maven project tree, if this two are open source project going through same build cycle it must have one already, if they are not related but related for your usecase then you can temporarily create a maven tree on top of these 2 projects and build the top parent it will build from bottom up in one command

it will find the leaf project, build it install it in maven's cache and now while building projectA it will refer it from maven's cache so no need to deploy to sonatype

A: You can also point project2 to build using offline mode :
mvn -o package

Then you drop the upload part of the project1 build to the remote repo.
Check the following link: Intro to repositories and How do I configure Maven for offline development?


text:
Q: Check when program started in Windows Is there any way to check when the program has started in Windows XP Pro? I tried with task manager I couldn't see when program has started.

A: I use Process Explorer from Sysinternals/Microsoft as a task manager replacement.  It includes start time and much more.

A:
Is there any way to check when the
  program has started in Windows XP Pro?

Anvir Task Manager will show this detail, when you hover over a program/service.

A free and portable version is available.


text:
Q: get age of git commit using hash If we have a git commit hash:
42f35295744738750a665dc846400c8040659d03

is there a way to determine/calculate the date it was created without any more info?

A: Not exactly, no.  You can easily extract either of the two time-stamps (author-date and committer-date) but neither one necessarily has anything to do with the actual creation date.  For instance:
$ GIT_AUTHOR_DATE='1970-1-1 00:00:00' GIT_COMMITTER_DATE='1970-1-1 00:00:00' git commit -m gotcha
[master (root-commit) 30e9626] gotcha
 1 file changed, 1 insertion(+)
 create mode 100644 foo
$ git log --pretty=fuller | sed 's/@/ /'
commit 30e9626dce78fd41c7ef6fae317e0ed61863f0cd
Author:     Chris Torek <chris.torek gmail.com>
AuthorDate: Thu Jan 1 00:00:00 1970 -0800
Commit:     Chris Torek <chris.torek gmail.com>
CommitDate: Thu Jan 1 00:00:00 1970 -0800

    gotcha

But, if you are not worried about the computer clock being wildly wrong and/or users deliberately faking their time-stamps, use %at or %ct or any of the variants of those to extract the author or committer time stamps:
$ git log --no-walk --format=%at HEAD
28800
$ git log --no-walk --format=%cd HEAD
Thu Jan 1 00:00:00 1970 -0800

See the PRETTY FORMATS section of the git log documentation for details.


text:
Q: Getting same wrong result from query in PHP I have one problem, when i do my query I always get same result (2), it doesn't get right ID value:
    $query = $this->mysqli->real_escape_string("SELECT id FROM image WHERE file_name = ?");

    $stmt = $this->mysqli->prepare($query);
    $stmt->bind_param("s", $this->name);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id);

    if($stmt->num_rows == 1)
    {
        var_dump($stmt->id);
        var_dump($id);
    }

Result is always:
$int(2)
NULL

And I dont even have that ID value in that table.
Notice: This query works in phpmyadmin.

A: Please RTM how to use mysqli:
$stmt = $this->mysqli->prepare("SELECT id FROM image WHERE file_name = ?");
$stmt->bind_param("s", $this->name);
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();

var_dump($id);

*

*you don't escape the whole query

*you don't need store_result

*you need fetch

*you need to var_dump the variable you have bound, not some other variable like $stmt->id

A: You don't need to use the escaping function, especially on the whole query string. That's a low-level function for exceptional circumstances.
Putting the query directly into the prepare call should fix it.


text:
Q: Codename One Background Operations We are busy developing an app that has the following requirements,

*

*Track the user's location throughout the day so that we can plot his/her route on a map

*The app should store all information locally on the device and when the device is able to connect to the server, it should auto-sync its data.

For this, we are trying to use the Background Location and Background Fetch functions.
We created a proof of concept app that does the following,

*

*Location Tracking: The location listener simply writes its coordinates to a SQLite database on the device for later use.

The setting of the Background Listener
        LocationManager locMan = LocationManager.getLocationManager();

    if (locMan == null) {
        Dialog.show("Location Error", "Location Manager not found", "OK", null);
    } else {
        if (!locMan.isGPSDetectionSupported()) {
            Dialog.show("Location Error", "GPS detection not supported.", "OK", null);
        } else {
            if (!locMan.isGPSEnabled()) {
                Dialog.show("Location Error", "GPS not enabled. Please close the app, turn on your location and try again.", "OK", null);
            } else {
                if (locMan.isBackgroundLocationSupported()) {
                    locMan.setBackgroundLocationListener(LocationListener.class);
                    Dialog.show("Location", "Background location listener loaded.", "OK", null);
                } else {
                    Dialog.show("Location Error", "Background location not supported", "OK", null);
                }
            }
        }
    }

And the the Listener Class itself,
public class LocationListener implements com.codename1.location.LocationListener {

@Override
public void locationUpdated(Location arg0) {
    String msg = arg0.getLatitude() + " - " + arg0.getLongitude();

    ASDTester.logMsg(ASDTester.MSG_LOC_COORDS, msg);
}

@Override
public void providerStateChanged(int arg0) {
    String msg = "" + arg0;

    ASDTester.logMsg(ASDTester.MSG_LOC_STATE_CHANGED, msg);
}

}
The call to ASDTester.logMsg(int type, String msg) simply creates a record in the SQLite database table

*Background Fetch: The performBackgroundFetch implementation also logs a message to the SQLite DB storing the timestamp of when the method fired,

Setting Background Fetch Interval,
if (Display.getInstance().isBackgroundFetchSupported()) {
        Display.getInstance().setPreferredBackgroundFetchInterval(60);
        Dialog.show("Background", "Background Fetch Interval set", "OK", null);
    } else {
        Dialog.show("Background Error", "Background Fetch Not Supported", "OK", null);
    }

Implementing performBackgroundFetch
    @Override
    public void performBackgroundFetch(long arg0, Callback<Boolean> arg1) {
       logMsg(MSG_BGF_TIMESTAMP, System.currentTimeMillis() + "");

        arg1.onSucess(Boolean.TRUE);
}

And then finally the Build Hints for iOS,
ios.background_modes=fetch,location

The implementation does not work on Android or iOS.
The location listener only fires once when it is initialized.
And the Background fetch does not fire at all.

*

*Are we doing something wrong in our implantation of these functions?

*How would one go about debugging these functions to try and see what is going wrong?


text:
Q: Add ASCII comments to a C binary? I have extrememly small amount of experience with C programming.
The operating system is Linux. When you do less on a program file it shows a bunch of random characters, but it also shows some of the readable ASCII characters in the original C source code.
Is there a way to force comments to show up in the binary, preferably near the beginning of the program file so that someone could get an idea of what this is used for? The formatting of the comments does not have to be pretty, a continuous line of text is fine.

A: Comments are only present in the source code and will not be present in the binary. In case you find any readable text in the binary, it is because you came across string literals used by the program.
Binaries should only be read by computers and not humans, so it doesn't make any sense to include comments in them anyhow.
If you would for reasons unknown need something like a binary with comments, then generate a disassembly from the C source. It will contain the machine code together with the C code and C code comments.
That being said, you could force the program to link a string to the binary even if that string isn't used by the program, by adding something like:
volatile const char foo [] = "STOP LOOKING AT MY BINARY!";

A: In some formats, you can add text strings to an object file (program files are also object files, the term "binary" is missleading as this includes all non-text files) in a special section. However, this requires a deeper knowledege about C and the format of object files and is implementation/OS specific.
You can - OTOH - print some explanatory text from your program. Just try less -h for an example.

A: Binaries should not be streamed with the less utility, and in less enlightened days you could seriously jack up your terminal settings by doing so.  It's safer to use the strings or objdump utilities to search for strings in binaries.
There's no good way to add comments to a binary file as such; binary formats are not meant to be human-readable, and don't generally allow free-form text.  As Lundin suggests, you can add some string objects to your source code that can be extracted from the compiled binary. Here's an example using the objdump facility:
#include <stdio.h>

int main( void )
{
  const char *str = "This is a test of the Emergency Broadcast System.";
  puts( str );
  return 0;
}

After compiling, we can extract the constant string data as follows:
[fbgo448@n9dvap997]~/prototypes/words: objdump -d -j.rodata -C foo

foo:     file format elf64-x86-64

Disassembly of section .rodata:

0000000000400610 <_IO_stdin_used>:
  400610:       01 00 02 00 00 00 00 00 54 68 69 73 20 69 73 20     ........This is
  400620:       61 20 74 65 73 74 20 6f 66 20 74 68 65 20 45 6d     a test of the Em
  400630:       65 72 67 65 6e 63 79 20 42 72 6f 61 64 63 61 73     ergency Broadcas
  400640:       74 20 53 79 73 74 65 6d 2e 00                       t System..

In the ELF format, string constants are stored in the .rodata section of the binary file.
This is about as pretty as it gets, though.


text:
Q: On subspaces of Hilbert spaces Let $H$ be a Hilbert space and $S$ be a subspace of $H$. Let $x\in H$ and $\lvert\lvert x\rvert\rvert=1$. Prove that $$\inf_{z\in S^\perp}\lvert\lvert x-z\rvert\rvert=\sup\{\lvert\langle x,y\rangle\rvert :y\in S, \lvert\lvert y\rvert\rvert\leq1\}.$$
I am not a functional analysis person but I need to solve a few problems for some tests. Any hints would be helpful. If someone can point me the underlying philosophy and mechanics of such a problem, it shall be great. As this problem stands now, I do not have a feel for what is actually going on here.
Thanks in advance!

A: Let's start with the left hand side but lets replace the norm with the norm squared, since if we minimize the norm squared we also minimize the norm. We can decompose $x$ on the two subspaces $S$ and $S^\perp$ in the following way,
$$x = x_S + x_{S^\perp},\quad x_S\in S,\quad x_{S^\perp}\in S^\perp$$
Substituting that into the l.h.s gives,
$$\inf\limits_{z\in S^\perp}\Vert x_S+x_{S^\perp} - z\Vert^2$$
Now, there is a theorem (in fact, it is the Pythagorean theorem for Hilbert spaces) which says $\Vert x+y\Vert^2 = \Vert x\Vert^2 + \Vert y\Vert^2$ if $x$ and $y$ are orthogonal. We know that $x_{S^\perp}-z$ is an element of $S^\perp$ because it is a subspace and $z\in S^\perp$. We also know, since $x_S\in S$, that $x_S$ is orthogonal to $x_{S^\perp}-z$. Thus we can write the following,
$$\inf\limits_{z\in S^\perp}\Vert x_S+x_{S^\perp} - z\Vert^2 = \inf\limits_{z\in S^\perp}\Big(\Vert x_{S^\perp} - z\Vert^2 + \Vert x_S\Vert^2\Big) = \Vert x_S\Vert^2 + \inf\limits_{z\in S^\perp}\Vert x_{S^\perp} - z\Vert^2$$
Since $x_{S^\perp}\in S^\perp$ we can take $z=x_{S^\perp}$ to get,
$$\inf\limits_{z\in S^\perp}\Vert x-z\Vert^2 = \Vert x_S\Vert^2\implies \inf\limits_{z\in S^\perp}\Vert x-z\Vert =\Vert x_S\Vert.$$

Now let's focus on the right hand side. We will use the same decomposition for $x$ as above but now we will use orthogonality and then the Cauchy Schwarz inequality.
$$\sup\limits_{y\in S, \vert y\vert\leq 1}\vert \langle y,x_S+x_{S^\perp}\rangle\vert = \sup\limits_{y\in S, \vert y\vert\leq 1}\vert \langle y,x_S\rangle\vert$$
The term we are taking the supremum of has an upper bound given by the CS inequality,
$$\vert \langle y, x_S\rangle \vert\leq \Vert y\Vert \Vert x_S\Vert\leq\Vert x_S\Vert$$
where the last inequality is due to our assumption that $\Vert y \Vert \leq 1$. Equality for the CS inequality is attained if the two vectors are linearly dependent, i.e. $y=\alpha x_S$ for some scalar $\alpha$. Since we are choosing $y$ to be in the unit ball, take $y=\frac{x_S}{\Vert x_S\Vert}$ which gives,
$$\sup\limits_{y\in S, \vert y\vert\leq 1}\vert \langle y, x_S\rangle\vert = \Vert\frac{x_S}{\Vert x_S\Vert}\Vert\Vert x_S\Vert = \Vert x_S\Vert$$

Thus the two sides are equal.

A: By continuity of the inner product, we may assume that $S$ is closed.
Write $x=Px+Qx$ where $P$ and $Q$ are the canonical projections on $S$ and $S^{\perp}$ respectively.
Then, $\inf_z\|x-z\|=\|Px\|.$
Now, the Hahn Banach theorem (applied to $S$) shows that
$\|Px\|=\sup\{|L(Px)|:L\in \mathscr L(S,\mathbb C);\ \|L\|=1\}.$
And, by the Riesz theorem, there is a $w\in S$ such that $Ls=\langle s,w\rangle$, and $\|w\|=1$ so
$\|Px\|=\sup\{|\langle Px,w\rangle :w\in S;\ \|w\|=1\}=$
$\sup\{|\langle Px+Qx,w\rangle :w\in S;\ \|w\|=1\}=$
$\sup\{|\langle x,w\rangle :w\in S;\ \|w\|=1\},$
as desired.


text:
Q: Fortran technical query I have the following function signature in Fortran. I am new to the Fortran language - what is meant by 0. in the function below?
ANTY(IAN,NA,0.,0.)

A: The notation 0. with a decimal point represents a floating point number, while 0 without a decimal point represents an integer. This is an important distinction for some implementations of FORTRAN, where the programmer must ensure that data types are consistent between the caller of a subroutine and the subroutine itself.

A: It is equivalent to 0.0 as a 32 bit real number (float in C)