text:
Q: MySQL export to csv includes escape characters First time reader but first time posting here.
I am trying export a MySQL table to a .csv file. This works totally fine:

SELECT * INTO OUTFILE '/tmp/0405151831.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM temp;

So exporting isn't the issue at all. But when I go to open in Excel, the escape character '\' shows up with all special characters in the spreadsheet.
I'm learning with a full list of 20k+ items provided by a plumbing supplier (they sent me spread sheets and I have been saving them as .csv, importing and exporting with MySQL to fill tables and to dick around on my own). Their list contains a plethora of ", ', * and all the other crap that may normally need escaping in basically each line.
I tried to get just get rid of the ENCLOSED BY and ESCAPED BY statements but guess what? There's plenty of commas in there too.
How do I keep the escape character from being exported into the .csv?


text:
Q: how to change colors in a list density plot I have plotted a data set using a ListDensityPlot.
    plot1 = ListDensityPlot[Result2,
  ColorFunction ->(*(*(ColorData[
   "TemperatureMap"][#3]&)*)(*"SunsetColors"*)"Hue"*)
   ColorData["Rainbow"], PlotRange ->(*{{4,8},{0,0.01}}*)All,
  PlotLegends ->(*{{Blue,Green,Yellow},{10^-4,10^-2,10^0}}*)
   Automatic,(*BarLegend[{"TemperatureMap",{0.0,0.22}}],*)
  FrameTicks -> {{{{0.00, "0.000"}, {0.005, ""}, {0.01, ""}, {0.015,
       ""}, {0.02, "0.002", {0.01, 0}}, {0.025, ""}, {0.03,
       ""}, {0.035, ""}, {0.04, "0.004", {0.01, 0}}, {0.045,
       ""}, {0.05, ""}, {0.055, ""}, {0.06,
       "0.006", {0.02, 0}}, {0.065, ""}, {0.07, ""}, {0.075,
       ""}, {0.08, "0.008", {0.01, 0}}, {0.085, ""}, {0.09,
       ""}, {0.095, ""}, {0.1, "0.010", {0.01, 0}}},
     Automatic}, {Automatic, Automatic}},
  FrameTicksStyle -> Directive[FontSize -> 18, Bold],
  FrameLabel -> {Style["Time (ns)", 20, Bold, Black],
    Style["Space (km)", 20, Bold, Black]}(*,AspectRatio\[Rule]2/3*)]

and the plot looks like

Now I wish to change the colors of the plot manually. I have tried using the different ColorData options but how to choose each of the color individually. It might be easy but I am totally confused.
Please help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can Visual Studio Code `quick fix` interact with keyboard? I am using VS Code with the excellent vscodevim extension.  When I navigate to a code that has a Quick Action available I can ctrl + . to activate the drop down context menu.
Is there a way to select toggle through the list of available items using the keyboard - other then the arrows keys.  As a point of information, within Visual Studio it is possible using tab, this does not work in VS Code.

Why? 'cause I love my MS ARC keyboard but I hate the rocker arrow keys.

A: This is a known issue for linux users using vscode with advanced shortcuts like vim extension in your case, for some reason quick fix contextual menu is unattached from vscode shortcuts which makes shortcuts not work. A really easy workaround to use with a graphical interface is HotKey.
HotKey > https://github.com/autokey/autokey for Linux and create your own shortcut.


text:
Q: trouble converting function from vb to c# I am trying to migrate myself to only using C# (was/am a vb.net guy)
I am having trouble converting this vb.net function from a project Im migrating to C#
Public Shared Function GetHolidays(ByVal holidaysFile As String) As List(Of Date)
    Dim sAllDates() As String = File.ReadAllLines(holidaysFile)
    Return (From sDate In sAllDates Select CDate(sDate)).ToList()
End Function

holidaysFile is a text file that contains items like this;
01/01/2015
01/19/2015
02/16/2015
04/03/2015
05/25/2015
07/03/2015
09/07/2015
11/26/2015
12/25/2015
any help appreciated, and streamreader may be better way to read this?

A: You can do
public static List<DateTime> GetHolidays(string holidaysFile)
{
    string[] sAllDates = File.ReadAllLines(holidaysFile);
    return (from sDate in sAllDates select Convert.ToDateTime(sDate)).ToList();
}

A: This matches the original:
public static List<DateTime> GetHolidays(string holidaysFile)
{
    return File.ReadAllLines(holidaysFile).Select(d => Convert.ToDateTime(d)).ToList();
}

But it kills me to use a List like that unless there's a real need for it. The code below will allow you to do lazy evaluation, supports only keeping one line in RAM at a time, and often still works with no changes to the calling code — many of the same benefits as using a StreamReader. Note that it's also shorter, and can still be easily converted to a List if needed. While I'm here, since you're coming from a string, you might do better using the DateTime.Parse() method:
public static IEnumerable<DateTime> GetHolidays(string holidaysFile)
{
    return File.ReadLines(holidaysFile).Select(d => DateTime.Parse(d));
}

As a general rule, you're almost always better off writing code to return an IEnumerable<T> instead of a List<T>. You have very little to lose, because you can always just append .ToList() to the end of such a function when you need, and much to gain in terms of easier refactoring from one underlying collection type to another and potential performance improvements by reducing RAM use or avoiding looping over items in the List it later turns out you never needed.


text:
Q: URLs that 302 Redirect to the Play Store with "market://details" do NOT show in the network tab in Chrome We are using Chrome Puppeteer to verify that links are redirecting to the play store properly. However, we are seeing weird behavior on both Puppeteer and Chrome Desktop where links that 302 redirect to the play store do not show in the network tab--at all (well, for Puppeteer, it just gets stuck on the previous URL). As if the requests are never made.
To reproduce, you'll need a URL whose server responds with a 302 to a market link, such as market://details?id=com.kabam.marvelbattle. The network tab shows no activity when visiting this URL. Is this intentional? Is there a flag that can be used to show ALL network requests, no matter the response?
EDIT:
Example URL: http://appclk.me/store.php. With network tab open, visit this URL. You will see nothing happens, nothing shows in the network tab. Firefox DOES show this request.

A: I didn't figure out how to show all the requests in Chrome, but because my specific use case was Puppeteer, I'll post how it was solved with that:
Use the page.setRequestInterception(true) method to get all requests to fire in the request event. Then listen for the request event like so:
        // Set a listener for new requests
        page.on('request', request => {
            console.log(request.url);
            request.continue();
        });

The 302s and market link request events are fired.


text:
Q: Creating a PostgreSQL connection with Entity Framework and Npgsql. Error is failing trying to read from SQL Server Attempting to create above connection via Entity Framework config file, and upon running get the following error :

13:02:57.058 0 System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
  (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
System.ComponentModel.Win32Exception (0x80004005): The network path was not found

Seems to not be identifying that it is a PostgreSQL connection that I am trying to make.
<configuration>
    <configSections>
        <section name="entityFramework"
                 type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                 requirePermission="false" />
    </configSections>
    <connectionStrings>
        <add name="Test_Track"
             connectionString="server=localhost;user id=rouser;password=pass;Database=track;"
             providerName="Npgsql" />
    </connectionStrings>
    <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
        <providers>
            <provider invariantName="Npgsql"
                      type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" />
        </providers>
    </entityFramework>
    <system.data>
        <DbProviderFactories>
            <add name="Npgsql Data Provider" invariant="Npgsql"
                 description=".Net Data Provider for PostgreSQL"
                 type="Npgsql.NpgsqlFactory, Npgsql, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7"/>
        </DbProviderFactories>
    </system.data>

*

*EF: Version 6.0

*VS .NET Framework 4.5

*Npgsql.2.2.7

*Npgsql.EntityFramework.2.2.7

Any help at all would be greatly appreciated.
Cheers.

A: This error comes from the MS SQL Server Provider, not Npgsql.
The MSSQL Provider is trying to connect through Named Pipes which are a Windows only thing, not supported by Npgsql.
I would advise to review your configuration file and use Npgsql.NpgsqlConnectionFactory instead of SqlConnectionFactory as the link provided by magicandre1981 shows.


text:
Q: User B can sudo to an user A (not root or group admin) I'm newbie, so please help me :
 In system , only user 'execute_prog'(not in group admin) has permission to execute a program ABC.  Now, I want that user B can sudo as 'execute_prog' to execute this program. How can I do?
Many thanks

A: I think you may just be looking for the su command.
B@my-pc:~$ su exec_prog
exec_prog@pc:~$

Also if you'd like to allow user A to su as B without a password, you can edit /etc/pam.d/su and add the following lines
# Change 'exec_prog' to the user you want to allow user B to become
auth       [success=ignore default=1] pam_succeed_if.so user = execute_prog
# replace 'B' with your username
auth       sufficient   pam_succeed_if.so use_uid user = B

Hope this helps!


text:
Q: Почему нету стрелок карусели? Я пытаюсь сделать карусель как в этом примере, но у меня получается последовательность картинок? что не так с моим копированием? вроде все редиректы я подогнал, всё 1 в 1 ,но вместо карусели в 1 слоте 3 картинок, у меня они идут одна за другой в столбик...
https://themewagon.com/themes/finance-business-free-bootstrap-4-responsive-business-website-template/


text:
Q: unity3d xcode build for iOS "object is not signed at all" it's been some days we are encountering this problem for iOS build of our game.
problem started when we lost our development device (macbook pro-retina (Yosemite) - stolen, sadly).
Fortunately all code was saved in our mercurial repository. As we planned to launch our alpha test phase for the same day, we borrowed another macbook, updated it to "capitain" and Xcode 7.1, downloaded our certificates and provisioning profile from apple developer center and tried building a signed project. We seem to get the same error ever since "Object is not signed at all".
We revoked and renewed our certificates but the problem still persists. We clean the project every time before building.
We are somehow new to apple development and we hesitate to go with deep signing.
Our build is an iOS export of our unity3d project and the only framework we are using is AppoDeal.
We seem to have some additional information recently, saying "command/usr/bin/codesign failed with exit code 1"
Can it be because we are working with another person's laptop? (with apple we can't be sure). How can we have a more verbose log of error?
Any help and suggestion is appreciated.


text:
Q: How do you focus a class textbox in webkitbrowser? I have this code for putting text into a textbox in a website:
Website code:
<textarea class="chat_input">

    Enter text for chat here

</textarea>

Program Code:
message = txtMessage.Text;
foreach(Node txt in wb.Document.GetElementsByTagName("textarea"))
{
    if(((Element)txt).GetAttribute("Class") == "chat_input")
    {
        ((Element)txt).TextContent = message;
    }
}

But the problem is, it only puts the text in when the textbox is focused.
Is there any way I can focus the textbox so that I don't have to do it manually?

A: How about Element.focus method?
I don't know if your webkit binding is exposing that method, but its standard DOM method.
http://www.w3schools.com/jsref/met_html_focus.asp


text:
Q: How to deal with objects that sometimes have a field missing in lightning components I have a custom object that has fields that sometimes has data and sometimes doesn't.  I'm trying to loop through those fields in my component, but having big problems because the field doesn't show up on the objects where it is blank.
IE Object 1 has field, object 2 doesn't all are in a array returned to component.
So I figure maybe I can just test to see if the field is missing and add in something in javascript, but it's not even letting me do that.  For example if field's name is Tier__c,  and object variable name is prod
I've tried
try { if (prod.Tier__C) {} catch (e) { prod.Tier__c = '' }

if ($A.util.isEmpty(prod.Tier__C)

if (prod.hasOwnProperty(Tier__C)

But in all cases I get the error "Error during init [Cannot read property 'apply' of undefined]"
any ideas?
Thanks,


text:
Q: Sending json data to backend via HTTP POST in Ionic 4 not working. [Notice: Trying to get property of non-object] I try to send http request via http post in Ionic 4 to my PHP backend through URLhttp://myexamplehost#1.com/api and it gives me back Notice : trying to get property of non object....
When i send my json data through URL http://myexamplehost#1.com/api via postman it works just fine. I'm guessing my json data sent via http post in Ionic 4 is somehow wrong.
So i try to send my json data through my other URL https://myexamplehost#2.com/api via http post in Ionic 4 and long behold it works just fine.
Here's what the json i sent via postman :
{
  "id": "",
  "date": "2019-09-09",
  "name": "jason"
}

And here's what i sent via http post in Ionic 4 page.ts:
  mydata: Idata = {
    id:string;
    date:string;
    name:string
  }

   saveData(){
     this.dk.insertData(this.mydata).subscribe((result:any)=>{
       console.log(result['_body']);
     });

  }

Here's what the service method look like :
insertData(data:Idata){
    return this.http.post(this.configUrl+'?ins=true',data,{
      headers: { 'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT'
    }
    });

Here's what the backend look like :
if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
    print_r(json_encode($request));
//    echo json_encode($request->name."-".$request->date);
//    echo json_encode($request->tgl);
    $result = $obj->insData("example_tb","null,'".date('Y-m-d',strtotime($request->date))."','".$request->name."'");

So what i really want to know is that is it a CORS issues or is it a code issues in my situation right there? Because i do get an error message of origin has been blocked by CORS policy in a console though. How do i fix this issues?

A: I would like to point that Access-Control-Request-Method is a request header that is set by the browser on CORS preflight requests, and it can only have one value.
Where The Access-Control-Allow-Methods is a CORS response header, returned by backend.
Replace
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT'

With
'Access-Control-Request-Method': 'POST'

A: Below code works for Ionic 4.
app.module.ts
İmport HttpClientModule
import { HttpClientModule } from '@angular/common/http';

Add HttpClientModule to imports.
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [HttpClientModule],

Now on your other page.
Mine ucak.page.ts
import { HttpClient } from '@angular/common/http';
constructor(public http: HttpClient) {}

SendDataFu(){

     let postData =  {
      user: "doctoravatar@yahoo.com",
      t: "vlIj",
      zip: 94089,
      forecast: 7
  }

     this.http.post("https://json.penzance.org/request", postData,{observe: 'response'})
       .subscribe(data => {
         console.log(data);

        }, error => {
         console.log(error);
       });

   }


text:
Q: accessing a website hosted in a virtualbox from host I have Windows 2008 Server installed in a VirtualBox and I'd like to be able to access the default website (localhost) from the host OS (Windows 7).
In IIS, I have set a hostname for the default website, which I've named 'webserver'.
THen I've added the following line to my hosts file (dns)
127.0.0.1   webserver
Now, if I browse to http://webserver in the guest OS, it works just fine.
But how do I access it from the host OS ?

A: If your virtual machine is connected to the internet, it's basically using your physical PC as a router.  That is, the host OS is assigning some private address (e.g. 192.168.X.X).
You need to put that in your browser to access the virtual server from the host OS.  I've never used Windows Server, but under Windows you'd find your IP by typing
ipconfig

at the command prompt.

A: Go your Virtual Machine's network settings in Virtualbox.
Set the network card not as attached through NAT, but through BRIDGED ADAPTER.
If you have multiple adapters on your host machine, select the main one, the one you're using to obtain an IP from your router.
Now your guest virtual machine is on the same network as your host's.
Hence you can simply access the webserver through the Virtual Machine's computer name. Ex.  http://virtserv
(Mind well: not the virtual machine's name in Virtualbox, but the COMPUTER NAME in the guest windows installation).

A: As far as I know the default IP address for virtual box if using NAT is 10.0.2.15, but still you can verify that using ipconfig.
Nat enables you to access your virtual box guest OS even if your host OS is not connected to a router/access point.
You can map a port from your host OS to the guest OS as follows.

*

*Got to your vbox guest OS's settings

*Click on the network Tab

*Make sure attached to is set to NAT

*Click on advanced then port forwarding

*Then you will see a screen where you can map host ports to guest ports

A: All you have to do is use the IP address of the host operating system.  In the host operating system open the command prompt and type ipconfig.  Find the IPv4 address:  E.G.
IPv4Address........ : 10.1.1.100--If there are multiple then try them all
Go into the Virtual Machine OS and open a browser.  Type the url:
http://10.1.1.100/optionalPathInfo
This will open the host IIS site from the VM browser.


text:
Q: Pass Values from Form -> Class -> Form C# I have 2 Forms: V.Batch and V.BatchEdit and a Class: M.Batch
In V.Batch there is a DataGrid. I want to pass the value I get from the DataGrid to V.BatchEdit and the get set method is in M.Batch.
The problem here is that the value isn't passed properly in V.BatchEdit. It returns 0.
Here is the code
V.Batch:
M.Batch bt;
public Batch()
    {
        bt = new M.Batch();
        InitializeComponent();
    }

 private void metroButton3_Click_1(object sender, EventArgs e)
    {
        bt.batchNum = Convert.ToInt32((metroGrid2.CurrentCell.Value).ToString());
        V.BatchEdit bEdit = new V.BatchEdit();
        this.Hide();
        bEdit.Show();

    }

M.Batch:
public int batchNum;

public int BatchNum
    {
        set { batchNum = value; }
        get { return batchNum; }
    }

V.BatchEdit
 static M.Batch bt = new M.Batch();
 DataSet a = bt.getBatch(bt.batchNum);
public BatchEdit()
    {
        db = new Database();
        InitializeComponent();
        System.Windows.Forms.MessageBox.Show(bt.batchNum.ToString() + "Batchedit");
        try
        {

            metroTextBox1.Text = a.Tables[0].Rows[0][2].ToString();
        }
        catch (Exception exceptionObj)
        {
            MessageBox.Show(exceptionObj.Message.ToString());
        }

    }

I'm new to coding and c#. I'm not sure if I placed static even though it should not be static or what.

A: Yes, you are using static improperly here.
The easiest way to see what's going wrong is to notice that you are calling new M.Batch() twice. That means you have two different instances of M.Batch in your application. And nowhere in your code do you attempt to share those instances.
What you should be doing is passing your instance of M.Batch from one form to another, e.g. in the constructor:
// V.Batch
bt.batchNum = Convert.ToInt32((metroGrid2.CurrentCell.Value).ToString());
V.BatchEdit bEdit = new V.BatchEdit(bt);
this.Hide();
bEdit.Show();

// V.BatchEdit
private M.Batch bt;
private DataSet a;

public BatchEdit(M.Batch batch)
{
  this.bt = batch;
  this.a = this.bt.getBatch(bt.batchNum)

  // Rest of your code here.
}

A: If You don't need the 'M.Batch' class for something else and you only use it for passing the value to V.BaychEdit, just declare a public property in V.BatchEdit like you did in M.Batch and use it like this:
V.BatchEdit bEdit = new V.BatchEdit();
bEdit.BatchNum = Convert.ToInt32((metroGrid2.CurrentCell.Value).ToString());

Your problem is that although your using statics you're still assigning a new instance to the static field.


text:
Q: Input mouse position not captured accurately? I am getting the Mouse-Input to draw a line onto a Texture from point A to point B. I've realized that I am not hitting every pixel, so moving my Mouse from the very left to the very right of the screen, it will skip some values, leading to gaps. When I move my mouse slowly it get's better.
I am getting the mouse position using:
var viewPortPosition = Camera.main.ScreenToViewportPoint (Input.mousePosition);

A: What I've ended up doing is running the so far collected mouse Positions through a Bresenham's Line Drawing function to rasterize the lines.
Source:
    public void line(Vector2 pointA, Vector2 pointB, Texture2D texture) {
    int x = (int)pointA.x;
    int y = (int)pointA.y;

    int x2 = (int)pointB.x;
    int y2 = (int)pointB.y;

    int w = x2- x ;
    int h = y2 - y;
    int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
    if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ;
    if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ;
    if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ;
    int longest = Math.Abs(w) ;
    int shortest = Math.Abs(h) ;
    if (!(longest>shortest)) {
        longest = Math.Abs(h) ;
        shortest = Math.Abs(w) ;
        if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ;
        dx2 = 0 ;
    }
    int numerator = longest >> 1 ;
    for (int i=0;i<=longest;i++) {
        texture.SetPixel (x, y, Color.red);

        numerator += shortest ;
        if (!(numerator<longest)) {
            numerator -= longest ;
            x += dx1 ;
            y += dy1 ;
        } else {
            x += dx2 ;
            y += dy2 ;
        }
    }
}

Original Source of Code but modified for Unity C#: All cases covered Bresenham's line-algorithm

A: If you want to draw a line I suggest you using the line renderer. Assuming you implemented the code in the Update() function - this is called every frame rendered. So even though your movement is quite slow, obviously it is already sufficient enough to leave gaps in your drawn lines.
Below is some code from this link which should work fine for you:
using System.Collections.Generic;
 using UnityEngine;

 [RequireComponent(typeof(LineRenderer))]
 public class LineRendererTest : MonoBehaviour
 {
     List<Vector3> linePoints = new List<Vector3>();
     LineRenderer lineRenderer;
     public float startWidth = 1.0f;
     public float endWidth = 1.0f;
     public float threshold = 0.001f;
     Camera thisCamera;
     int lineCount = 0;

     Vector3 lastPos = Vector3.one * float.MaxValue;

     void Awake()
     {
         thisCamera = Camera.main;
         lineRenderer = GetComponent<LineRenderer>();
     }

     void Update()
     {
         Vector3 mousePos = Input.mousePosition;
         mousePos.z = thisCamera.nearClipPlane;
         Vector3 mouseWorld = thisCamera.ScreenToWorldPoint(mousePos);

         float dist = Vector3.Distance(lastPos, mouseWorld);
         if(dist <= threshold)
             return;

         lastPos = mouseWorld;
         if(linePoints == null)
             linePoints = new List<Vector3>();
         linePoints.Add(mouseWorld);

         UpdateLine();
     }

     void UpdateLine()
     {
         lineRenderer.SetWidth(startWidth, endWidth);
         lineRenderer.SetVertexCount(linePoints.Count);

         for(int i = lineCount; i < linePoints.Count; i++)
         {
             lineRenderer.SetPosition(i, linePoints[i]);
         }
         lineCount = linePoints.Count;
     }


text:
Q: base64 to file response not working Due to development restrictions we are sending all the data in base64 from client to server, also the uploaded files (pdf or txt files). Those files are being correctly stored in mysql database as LONGBLOB after this procedures in java:
decoder = new BASE64Decoder();
decodedBytes = decoder.decodeBuffer(request.getParameter("fic_adjunto"));
ficheroAdjunto = new SerialBlob(decodedBytes);

But when I want to download some file from jsp, I'm using this servlet code with an html link:
jsp-file:
<a href='GestionDescargas?valor=LoadFile&IdEvent=26'>

Server-side:
Conexion oConexion = new Conexion();
            Evento oEvento = new Evento();
            oEvento = oConexion.RecuperaEventoByIdEvento(Integer.parseInt(request.getParameter("IdEvent")));

            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=" + oEvento.getNomFicheroAdjunto());

            Blob fileBlob = oEvento.getFicheroAdjunto();
            int blobLength = (int) fileBlob.length();
            byte[] blobAsBytes = fileBlob.getBytes(1, blobLength);
            String base64String = Base64.encodeBase64String(blobAsBytes);

            InputStream is = new ByteArrayInputStream(base64String.getBytes("UTF-8"));

            int read=0;
            byte[] bytes = new byte[BYTES_DOWNLOAD];
            OutputStream os = response.getOutputStream();

            while((read = is.read(bytes))!= -1)
            {
                os.write(bytes, 0, read);
            }
            os.flush();
            os.close();

Im quite new in this programming world, could you give me a hand please?. I have tried everything but only getting the base64 string (and is not even equal to the original but almost)
Original base64 string:
data:text/plain;base64,VGFibGEgZGUgaGlzdG9yaWNvIGNhdGVnb3LtYXMgeSBkZSBwcm9kdWN0b3MsIHBhcmEgZWwgY2llcnJlIGRlZmluaXRpdm8gZGVsIGV2ZW50by4NCg0KQWwgZWxpbWluYXIgdW5hIGNhdGVnb3JpYSwgc2UgZWxpbWluYW4gdG9kb3Mgc3VzIHByb2R1Y3Rvcy4NCg0KQWwgZWxpbWluYXIgdW4gcHJvZHVjdG8sIHNlIGVsaW1pbmEgZGUgdG9kb3MgbG9zIHNpdGlvcyBlbiBsb3MgcXVlIGVzdOkgc2llbmRvIHVzYWRvLg0KDQoJLVNlIGVsaW1pbmEgZGVsIGFsbWFj6W4uDQoJLVNlIGVsaW1pbmEgZGUgbGFzIHBsYW50aWxsYXMuIChzYW1jYXQucGxhbnRpbGxhX3Byb2R1Y3RvKQ0KCS1TZSBlbGltaW5hIGRlbCBzaXN0ZW1hIGRlIGdlc3Rpb24gZGUgYWxlcnRhcy4gKHNhbWNhdC5hbGVydGFfcmVzZXJ2YSkNCgktU2UgZWxpbWluYSBkZSBsb3MgZXZlbnRvcyBubyBGSU5BTElaQURPUyArIFBvc2libGVzIHJvdHVyYXMgKyBBQ1RVQUxJWkFDSdNOIFBSRUNJTyBGSU5BTCAoc2FtY2F0LnBlcmRpZGFfZXZlbnRvLCBzYW1jYXRfcHJvZHVjdG9fZXZlbnRvKQ0KDQoNCg0KQWxlcnRhcywgc29sbyB1bmEgdmV6IGVsIG1pc21vIHByb2R1Y3RvIHBvciBhbGVydGE=

Decoded from database string:
data/text/plain/base64/VGFibGEgZGUgaGlzdG9yaWNvIGNhdGVnb3LtYXMgeSBkZSBwcm9kdWN0b3MsIHBhcmEgZWwgY2llcnJlIGRlZmluaXRpdm8gZGVsIGV2ZW50by4NCg0KQWwgZWxpbWluYXIgdW5hIGNhdGVnb3JpYSwgc2UgZWxpbWluYW4gdG9kb3Mgc3VzIHByb2R1Y3Rvcy4NCg0KQWwgZWxpbWluYXIgdW4gcHJvZHVjdG8sIHNlIGVsaW1pbmEgZGUgdG9kb3MgbG9zIHNpdGlvcyBlbiBsb3MgcXVlIGVzdOkgc2llbmRvIHVzYWRvLg0KDQoJLVNlIGVsaW1pbmEgZGVsIGFsbWFj6W4uDQoJLVNlIGVsaW1pbmEgZGUgbGFzIHBsYW50aWxsYXMuIChzYW1jYXQucGxhbnRpbGxhX3Byb2R1Y3RvKQ0KCS1TZSBlbGltaW5hIGRlbCBzaXN0ZW1hIGRlIGdlc3Rpb24gZGUgYWxlcnRhcy4gKHNhbWNhdC5hbGVydGFfcmVzZXJ2YSkNCgktU2UgZWxpbWluYSBkZSBsb3MgZXZlbnRvcyBubyBGSU5BTElaQURPUyArIFBvc2libGVzIHJvdHVyYXMgKyBBQ1RVQUxJWkFDSdNOIFBSRUNJTyBGSU5BTCAoc2FtY2F0LnBlcmRpZGFfZXZlbnRvLCBzYW1jYXRfcHJvZHVjdG9fZXZlbnRvKQ0KDQoNCg0KQWxlcnRhcywgc29sbyB1bmEgdmV6IGVsIG1pc21vIHByb2R1Y3RvIHBvciBhbGVydGA==

What I want is to get the original file anyway... and not the base64 string.
Thank you very much!!!!

A: Maybe the problem is related to the way that you are using to send the file, for example if the file is encoded with iso-8859-1, you need to do the next (because you read the BLOB with UTF-8):
decoder = new BASE64Decoder();
decodedBytes = decoder.decodeBuffer(new String(request.getParameter("fic_adjunto").getBytes("iso-8859-1"), "UTF-8"));
ficheroAdjunto = new SerialBlob(decodedBytes);

The code above will be useful only if you are sending the file in iso-8859-1 format, to avoid this (re-format the String) you need to force the request to send in UTF-8 format.


text:
Q: Which file we shouldn't commit on GitHub from Android Studio I am working on a project using Android Studio, I am using GitHub and SourceTree also.
The problem is when I make change in my project and open SourceTree then I see some files on Unstaged Files list like:

*

*.idea/mics.xml

*.idea/modules.xml

*.idea/vcs.xml

*ProjectName.iml

*app/app.iml

*app/build.gradle

*setting.gradle

I don't know these files should be ignored or committed after changes in the code. Please suggest.
Here is the .gitignore file under app folder.
# Built application files
/*/build/

# Crashlytics configuations
com_crashlytics_export_strings.xml

# Local configuration file (sdk path, etc)
local.properties

# Gradle generated files
.gradle/

# Signing files
.signing/

# User-specific configurations
.idea/libraries/
.idea/workspace.xml
.idea/tasks.xml
.idea/.name
.idea/compiler.xml
.idea/copyright/profiles_settings.xml
.idea/encodings.xml
.idea/misc.xml
.idea/modules.xml
.idea/scopes/scope_settings.xml
.idea/vcs.xml
*.iml

# OS-specific files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

A: Check out links below:
gitignore/JetBrains.gitignore at master · github/gitignore · GitHub - for Android Studio
gitignore/Android.gitignore at master · github/gitignore · GitHub - for Android itself


text:
Q: Css/javascript position Well, this is my problem:

I need the red box behind the number , not above.
My css:
[data-counter]:after {
    background-color: #FF6969;
    background-image: -webkit-linear-gradient(#FF6969 0%, #ff0000 100%);
    background-image: -moz-linear-gradient(#FF6969 0%, #ff0000 100%);
    background-image: -o-linear-gradient(#FF6969 0%, #ff0000 100%);
    background-image: -ms-linear-gradient(#FF6969 0%, #ff0000 100%);
    background-image: linear-gradient(#FF6969 0%, #ff0000 100%);
    height: 8px !important;
    margin-top: 4px;
    content: attr(data-counter);
    top: -10px;
    position: absolute;
    padding: 1px 4px;
    box-shadow: 0 1px 2px rgba(0,0,0,.5), 0 1px 4px rgba(0,0,0,.4), 0 0 1px rgba(0,0,0,.7) inset, 0 10px 0px rgba(255,255,255,.11) inset;
    background-clip: padding-box;
    font:bold 10px "Helvetica Neue", sans-serif;
    color: white;
    text-decoration: none;
    text-shadow: 0 -1px 0 rgba(0,0,0,.6);
    margin-left: -10px;

}

My javascript(lol)
$(function () {
    $('head').append('');
    $('#inbox_link').prepend('

');
    var newMPs = ".main-content .statused .tcl.tdtopics:has(img[src='http://illiweb.com/fa/empty.gif?NEW']) a[href*='/privmsg?folder=inbox&mode=read&p']";
    $('#numberMps').load('privmsg?folder=inbox ' + newMPs, function () {
        $('#numberMps').after('

');
        var sizeMPs = $('#numberMps a').size();
        if (sizeMPs == '0') return;
        $('li a[href^="/privmsg?folder=inbox?BOX"]').attr('data-counter', ''+sizeMPs+'');
    });
});

Look, the javascript obatin the number of messages, and the css draw this.
Anyone have tips or a solution?

A: Try useing z-index, it should help.


text:
Q: ITransferProgress and tracking data from attachments in MailKit I asked similar question earlier: How to check amount of sent/received data in MailKit? but now I'm talking about something else.
I have class that implements ITransferProgress interface. In this class I'm tracking transfer data and calculate speed. In my sendMessage method I create class object and update speed in table every one second:
ITransferProgressClass progress = new ITransferProgressClass();
//some code
progress.startTimer();
progress.SpeedCell = myRow.Cells[3];
client.Send(message, cancellationToken, progress);
progress.stopTimer();

And it works very good. I want to do something like this in downloadMessage method:
ITransferProgressClass progress = new ITransferProgressClass();
//some code
progress.startTimer();
progress.SpeedCell = myRow.Cells[3];
readyMessages.Add(client.Inbox.GetMessage(readySubjects[list[i]].UniqueId, cancellationToken, progress));
progress.stopTimer();

But every timer tick I'm getting 0 value. Why?

A: The download progress ends when the message gets returned by GetMessage(), it doesn't get used when you iterate over the attachments in the loop after that method is called.


text:
Q: jQuery For Loop with Post Not Counting Correctly So, I have the following line of code, that does a for loop and subjects 12 on every loop.
If I alert right before the post, it alerts the numbers as you would expect (72, 60, 48, 36, 24).
But, with the alert inside the post it alerts the number 12 five times.
Any idea why that is? Any idea where the number 12 is coming from?
function loadEstimates(option){
    for(term_length=72; term_length>=24; term_length-=12){
        var post_options = {loadEstimates: 'true', coverage_option:option, term_length:term_length};
        $.post('../includes/process.php', post_options, function(response, status){
            alert(term_length);
        });
    }
}

The second part of the question is, I want to output these in order and I've noticed on occasion the post will output something random like 36, 48, 24, 72, 60 because of server response times. How can I put the 'response' from the post into an array or something that will let me sort it before displaying it?
Thanks!!
/////// EDIT ////////
Okay, so I took some of ChessWhiz's advice and used an array and came up with.
function loadEstimates(option){
    var term_length = new Array('72','60','48','36','24');
    var term_length_output = new Array(5);
    $.each(term_length, function(index, t_length){
        var post_options = {loadEstimates: 'true', coverage_option:option, term_length:t_length};
        $.post('../includes/process_instantquote.php', post_options, function(response, status){
            term_length_output[t_length] = response;
        });
    });

    alert(term_length_output);
}

This also solves my potential future conundrum of if I decide to use a number in the term_length that isn't divisible by 12.
But, the term_length_output is still blank. Any idea what I am doing wrong with that?

** FINAL EDIT *****
Here is the code I ended up using. It does exactly what I need it to do. It's probably not the most 100% correct way, but it works.
Thank you all very much for your answers and help!!!
function loadPriceEstimates(option){
    $('#package-term-options table tbody').append('

').show();
    var term_length = new Array('72','60','48','36','24');
    var term_length_output = new Array();
    var count = 0;
    $.each(term_length, function(index, t_length){
        var post_options = {loadPriceEstimates: 'true', coverage_option:option, term_length:t_length};
        $.post('../includes/process_instantquote.php', post_options, function(response, status){
            if(status == 'success'){
                term_length_output[t_length] = response;
                count++;
                if(count == 5){
                    term_length_output.sort();
                    term_length_output.reverse();
                    $('#package-term-options table tbody').html('');
                    $.each(term_length_output, function(index, value){
                        $('#package-term-options table tbody').append(value);
                    });
                }
            }
        });
    });
}

A: I think that's because the for loop body is not a scope for the callback function closure, the scope is the container function.
Try this:
function loadEstimates(option){
    for(term_length=72; term_length>=24; term_length-=12){
        postProcess(term_length);
    }
}

function postProcess(term_length) {
        var post_options = {loadEstimates: 'true', coverage_option:option, term_length:term_length};
        $.post('../includes/process.php', post_options, function(response, status){
            alert(term_length);
        });
}

For more info see:

*

*http://www.mennovanslooten.nl/blog/post/62

*http://www.javascriptkit.com/javatutors/closures.shtml

*http://en.wikipedia.org/wiki/Closure_%28computer_science%29

A: Using an index variable that counts backwards by 24's is prone to error. Instead, use a normal index, then calculate the term_length. Next, you can use an array to store the results. However, if the callback hasn't completed running, the array won't yet hold all the results. Lastly, you need to make a copy of the loop variable to escape the closure. Example:
function loadEstimates(option) {
    for(i = 0; i < 5; i++) {
        var resultsIndex = i;
        var term_length = 72 - (i * 12);
        var post_options = {loadEstimates: 'true', coverage_option:option, term_length:term_length};

        $.post('../includes/process.php', post_options, function(response, status){
            results[resultsIndex] = response;
        });
    }
}

Then, your results will be nicely aligned in the results array. The [12, 12, 12, 12, 12] side-effect caused by closure is basically caused because the last value of term_length is getting outputted every time, which is 24 - 12 = 12, due to the way the for loop modifies it and the function closes over it.

A: The problem has to do with the way for works: it uses the same variable throughout its lifespan (rather than instantiating new ones), meaning that same variable is being bound to your $.post() callback every time.  AJAX calls are asynchronous, and that callback isn't being called until after your loop has finished and term_length has made its way down to 12.
For a discussion of the general problem outside of JavaScript, see "Python's lambda is broken!"
The solution, then, is to, somehow or another, get JavaScript to instantiate a new variable every iteration so it's not changed out from under you during the looping.  One way to do that is to pass it through a function.  See Nicolas Bottarini's answer for the code.


text:
Q: Element in col shifts slightly when element in adjacent column is toggled Currently working on a weather app using bootstrap, and within one row I have two columns: one side shows the temperature, which can be toggled between C and F, and the other shows other basic weather information (right now I just have a basic weather description). But when I toggle the temperature between C and F, the differences in width of those two letters appears to push the weather info slightly to the left or right.
I've tried applying position:absolute/relative and floats to both elements, but can't seem to fix the problem. Any help would be appreciated!
All my code is in Codepen: https://codepen.io/alissaw/pen/pppzwd but here is the element-specific code isolated (#weatherdata is the element that's shifting):

          <input type="checkbox">

--- CSS ---
body{
  background-color: #4FCCFF;
  text-align: center;
  background-repeat: no-repeat;
  background-size: cover;
}
.container{
  background-color: rgba(0,0,0,0.1);
  width: 70%;
  margin: auto;
  overflow:hidden;
}
#location{
  text-align: center;
  font-size: 60px;
  color: white;
  font-family: Raleway;
  font-weight: 200;
}
#temp{
      font-size: 100px;
      font-family: Raleway;
      font-weight: 250;
      float: left;
      color: white;
    }

#weatherData{
  font-size: 40px;
  color: white;
  font-family: Raleway;
  font-weight: 200;
  margin-top: 5%;
  display: inline-block;
  position: absolute;
}

A: So in your codepen I noticed that you used bootstrap classes but did not add in the bootstrap CSS file. I added the CSS file in and it seemed to work just fine without the shifting.
From the settings try adding in the bootstrap file:
https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.3/css/bootstrap.css


text:
Q: Windows Phone 7 Dynamic Listbox and RSS feed problems I am having a huge problem with doing this, and I am hoping someone can take me under their wing and help guide me through this.
My problem is not knowing how to dynamically add more items to the listbox after getting the first set of 15 through my custom made RSS feed, tied to my website, into my windows phone 7.
I am thinking of limiting my RSS feed to 15 items, so that those who subscribe will not be inundated with thousands of items in the feed.
However, this poses a problem when coding for my phone. If I cap my RSS feed to the 15 most recent items, how can I obtain the prior ones outside of these 15, and the other problem, how to load them?
I already have my RSS feed classes, and I can successfully obtain my rss feed in my phone. That is not the problem. Again stated -- once I load my initial 15 items in the windows phone 7, how can I load additional sets of 15, if I keep my RSS items in my website xml kept to 15 items at a time (again, so that I don't have an RSS feed with 1000s of items every time a person loads it)
Any help is appreciated.
Page CS:
private void Button_Click(object sender, RoutedEventArgs e)
    {
        RssService.GetRssItems(
            WindowsPhoneBlogPosts,
            (items) => { listbox.ItemsSource = items; },
            (exception) => { MessageBox.Show(exception.Message); },
            null
            );
    }

Page XAML:
        <ListBox x:Name="listbox" Grid.Row="1" SelectionChanged="listbox_SelectionChanged" Style="{StaticResource ListBoxStyle1}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="60" />
                        </Grid.RowDefinitions>
                        <Image x:Name="aaa"  Grid.Row="0" HorizontalAlignment="Left" Height="60" Width="60" Source="{Binding Url}"/>
                        <TextBlock Grid.Row="1" Text="{Binding PublishedDate}" Foreground="Green" />
                        <TextBlock Grid.Row="2" TextWrapping="Wrap" Text="{Binding PlainSummary}" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Same page Xaml:
<phone:PhoneApplicationPage.Resources>
    <Style x:Key="ListBoxStyle1" TargetType="ListBox">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="BorderBrush" Value="Transparent"/>
        <Setter Property="Padding" Value="0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBox">
                    <ScrollViewer x:Name="ScrollViewer" Background="{TemplateBinding Background}">
                        <StackPanel>
                            <ItemsPresenter/>
                            <Button x:Name="thebutton" Content="Button" Visibility="{Binding LoadMore}"/>
                        </StackPanel>
                    </ScrollViewer>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</phone:PhoneApplicationPage.Resources>

A: You should read up about data virtualization, and about how to load data while scrolling, and lastly about the whole concept behind virtuailization in general.


text:
Q: REGEXP_SUBSTR in Teradata I am having data in a column like XXX/XXXX/XXXX/XYYUX/YYY. I am trying to extract only the first two digits after the 3rd backslash(/) in the column which is 'XY' in this example. Can you please help?
Thanks!

A: Try this:
    REGEXP_SUBSTR('XXX/XXXX/XXXX/XYYUX/YYY','^([^/]*/){3}\K..',1,1,'i')

'^' start of string
'([^/]*/){3}' looks for 0 or more non-slashes followed by a slash, 3 times
'\K' match reset operator drops the part of the string that has been matched up to this point
'..' grabs the next two characters in the string

A: Try using -  STRTOK('/88/209/89/132]', ' /]', 3)
returns the 3rd octet, '89'


text:
Q: Possibly 'undefined' error while compiling React code with onClick event I'm fighting with Fluent UI Nav Link issue which appears when you user React Router. When you use Nav component standalone everything works fine. The problem is when you try to use it with React Router - it seems there's no a proper way to modify Nav component to display and process Router links.
I found following thread on official Fluent UI repository on Github: https://github.com/microsoft/fluentui/issues/915
I'm trying different solutions people presented there, nothing works for me. Each one results in some kind of error during compilation.
The recent solution I wanted to use is:
<Nav
    onLinkClick={(element, event) => {
        event.preventDefault();
        history.push(element.url);
    }}
    styles={navStyles}
    groups={navLinkGroups}
/>

When compiling above code, each time I get following error:
Object is possibly 'undefined'.  TS2532

52 |                <Nav
53 |                    onLinkClick={(element, event) => {
54 |                            event.preventDefault();
   |                            ^
55 |                            history.push(element.url);
56 |                      }}
57 |                    styles={navStyles}

Is it because I'm using Typescript? What should I change?

A: Try with optional chaining:
event?.preventDefault()

The optional chaining operator provides a way to simplify accessing
values through connected objects when it's possible that a reference
or function may be undefined or null.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining


text:
Q: Why does my Bitlocked External HDD go read-only after I unlock it? Windows 10, AD-managed environment, WD My Passport external.
We had a new external HDD enter circulation, which per policy has to be bitlocked.  This being new, policy is also that it be fully reformatted (which I did as NTFS) and then Bitlocked in Compatible mode (with password).
The individual it was issued to ran into an issue on first use:  Couldn't write to it.  No files could be saved there, no files could be made there.
After some initial troubleshooting, I decided maybe I'd messed something up.  I reformatted it again, made sure all the permissions would allow any office user to write files (and I did test this and made a few files on the drive as my admin user and my regular user to make sure).  I then bitlocked it, unlocked it, and wrote another file to it to be sure. I then removed the drive from the machine.
Before I took it to the user in question though, I thought to try it again - attached the drive, successfully unlocked, and for no discernable reason it's write only again.  Files cannot be written there at all, even though it is unlocked and NTFS permissions allow for it.
Earlier troubleshooting involved having to decrypt the drive and reformat it to remove that condition; as I recall, Diskpart could select and claim to remove Write Only, but it wouldn't actually do it (drive still wouldn't accept files).
Digging around leads me nowhere; closest I get is someone claiming a GPO that denies non-bitlocked media may be set to deny_write, but that's not only not set but also non-sense in this case.
Has anyone run into this, and how did it get corrected?

A: I have figured it out:  Turns out the issue is the GPO "System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing".
Normally there's a red warning banner up at the top of the Password entry box for the drive decryption.  This did not display when I was initially interacting with the drive.  It was not until I took it to another machine that had not been involved with bitlocking that I saw it.
To get around this, you can set the drive to auto-unlock, enter the password, dismount / eject the drive in Windows, and then reattach.  Seems to work just fine now.
https://social.technet.microsoft.com/Forums/windowsserver/en-US/fb24213a-c7a7-4e4b-803c-6865ae7a91fe/bitlocker-group-policy-requires-that-for-this-drive-to-be-writable-either-autounlock-must-be-set?forum=winserver8gen


text:
Q: How to convert dictionary array into String? I have a base URL:
let baseURL = "https://t**.com"

I am receiving a dictionary, in which I have a method name, HubName, and an array which contains the data.
if let values = data as? [String: Any] {
            print("Method Name is: \(values[Types.method]!), Hubname: \(values[Types.hubName]!), messageReceived: \(values[Types.array]!)") }

Here is the response I get when I send a picture from the server:
Method Name is: ImageFromAgent, Hubname: NotificationHub, messageReceived: (
"Admin User",
16406,
"/api/WebChat/GetUpload?path=97511d99-887f-4ab9-96ac-d372d542097e-Screenshot 2022-09-07 at 7.36.05 PM.png"

)
Now in second index of Array, I have an image path which I want to append with my baseURL.
What Im trying is:
            if values[Types.method] as! String == MethodName.ImageFromAgent {
                let imageArr = values[Types.array] as? [Any]
                let imageUrl = baseURL + imageArr?[2] as! String
                print("imageUrl = \(imageUrl)")
            }

However, it is not converting it into a string and receiving error of
Binary operator '+' cannot be applied to operands of type 'String' and 'Any?'
If I do:
if values[Types.method] as! String == MethodName.ImageFromAgent {
                let imageArr = values[Types.array] as? [Any]
                print("imageUrl = \(imageArr![2])")
            }

Then I receive the image path, but I want to join the baseURL and the file path into a single string.

A: If you use optional unwrapping you can use ? operator to safely unwrap the value and there won't be a type inference problem
The below should solve your problem
if values[Types.method] as! String == MethodName.ImageFromAgent {
            if let imageArr = values[Types.array] as? [Any],
            let imageURlString = imageArr[2] as? Sting {
            let imageUrl = baseURL + imageURlString
            print("imageUrl = \(imageUrl)")
        }

Using a force-unwrap operator can crash your app abruptly. Also, you are using the index 2 and !.
Also, as a best practice try avoid force-unwrap unless you are sure there will be a non-null value all the time.


text:
Q: custom text filename postgres 9.6 I have a problem, I generate a function that creates a temporary table, and I use it to create a text file, until there is everything well generated that is what I need.
But in the name of the file that I create, I need to pass a parameter (basically the value of a column in a table in my database), but when trying to pass a value, I get an error or simply create the file with a name that It has special characters.
And so far tried the following:
CREATE OR REPLACE FUNCTION sp_campos_base2()
RETURNS TEXT AS $$

DECLARE
    registro TEXT DEFAULT '';
    var1 TEXT;
...
BEGIN

    var1 := 'LO_LOGRE';
....
EXECUTE $$COPY (select * from tmp1) to '/tmp/editores/prueba_$$ || var1 || $$_OMS.txt' WITH DELIMITER E'\t' CSV HEADER ENCODING 'LATIN1'$$;
.....
COPY (select * from tmp1) to '/tmp/editores/prueba_|| var1 ||_OMS.txt' WITH DELIMITER E'\t' CSV HEADER ENCODING 'LATIN1';
....

Until try with bash syntax:
COPY (select * from tmp1) to '/tmp/editores/prueba_`var1`_OMS.txt' WITH DELIMITER E'\t' CSV HEADER ENCODING 'LATIN1';
....

Is it possible to customize the file name with the COPY command?

A: eg:
do
$$
declare
var1 text := 'some';
begin
execute format('copy pg_database to %L','/tmp/'||var1||'.csv');
end;
$$
;

and check:
t=# \! head -n 2 /tmp/some.csv
postgres    10  6   C   UTF-8   f   t   -1  12668   858 1   1663    \N
t   10  6   C   UTF-8   f   t   -1  12668   858 1   1663    \N


text:
Q: How to specify FUN used in by( ) or related apply( ) functions In a by() function, I will use cor (correlation) to be the FUN there. However, I'd like to setup use="complete.obs" too.
I don't know how to pass this argument in the FUN = cor part.
For example,
by(data, INDICES=list(data$Age), FUN=cor)

A: probably
by(data, INDICES=list(data$Age), FUN=cor, use = "complete.obs")

will work.
the arguments to by are passed to FUN.

A: If you start looking around at various R help files for functions like by, you may start to notice a curious 'argument' popping up over and over again: .... You're going to see an ellipsis listed along with all the other arguments to a function.
This is actually an argument itself. It will collect any other arguments you pass and hand them off to subsequent functions called later. The documentation will usually tell you what function these arguments will be handed to.
In this case, in ?by we see this:
...  further arguments to FUN.

This means that any other arguments you pass to by that don't match the ones listed will be handed off to the function you pass to FUN.
Another common instance can be found in plot, where the documentation only lists two specific arguments, x and y. Then there's the ... which gathers up anything else you pass to plot and hands it off to methods or to par to set graphical parameter settings.
So in @kohske's example, use = "complete.obs" will be automatically passed on the cor, since it doesn't match any of the other arguments for by.

A: @kohske and @joran give equivalent answers showing built in features of by (which are also present in apply and the entire plyr family) for passing additional arguments to the supplied function since this is a common application/problem.  @Tomas also shows another way to specify an anonymous function which is just a function that calls the "real" function with certain parameters fixed.  Fixing parameters to a function call (to effectively make a function with fewer arguments) is a common approach, especially in functional approaches to programming; in that context it is called currying or partial application.
library("functional")
by(data, INDICES=list(data$Age), FUN=Curry(cor, use = "complete.obs"))

This approach can be used when one function does not use ... to "pass along" arguments, and you want to indicate the only reason that an anonymous function is needed is to specify certain arguments.

A: In general, you have 2 possibilities:
1) specify the arguments in the calling function (tapply() or by() in this case). This also works even if the key argument to fun() is not the first one:
fun <- function(arg1, arg2, arg3) { ... } # just to see how fun() looks like
tapply(var1, var2, fun, arg1 = something, arg3 = something2)
    # arg2 will be filled by tapply

2) you may write your wrapper function (sometimes this is needed):
tapply(var1, var2, function (x) { fun(something, x, something2) })


text:
Q: Angular 2 - too many package dependencies I have installed new version RC Angular 2. Everything works fine, but my requests for angular dependencies are very bad. I understand, then system js is loading this dependencies asynchronous, but I have still 285 requests! Is it all really needed? Complete transferred is about 3.3MB, it is very bad for me. I there way, how to do it more efficiently?
Here is my System JS config:
(function (global) {

    // map tells the System loader where to look for things
    var map = {
        'input': '/js/components', // 'dist',
        'rxjs': '/rxjs',
        'angular2-in-memory-web-api': '/angular2-in-memory-web-api',
        '@angular': '/@angular',
        'primeng': '/primeng'
    };

    // packages tells the System loader how to load when no filename and/or no extension
    var packages = {
        'input': { main: 'boot.js', defaultExtension: 'js' },
        'rxjs': { defaultExtension: 'js' },
        'angular2-in-memory-web-api': { defaultExtension: 'js' },
        'primeng': { defaultExtension: 'js' }
    };

    // meta tells the System loader how to load dependencies. In this case for custom scripts it is Global -> <script ... />
    var meta = {
        '/js/javascript.min.js': { format: 'global' },
        '/js/angularDep.min.js': { format: 'global' }
    }

    var packageNames = [
         '@angular/core',
         '@angular/platform-browser-dynamic',
         '@angular/compiler',
         '@angular/platform-browser',
         '@angular/common'
        // '@angular/compiler',
        // '@angular/core',
        // '@angular/http',
        // '@angular/platform-browser',
        // '@angular/platform-browser-dynamic',
        // '@angular/router',
        // '@angular/router-deprecated',
        // '@angular/testing',
        // '@angular/upgrade'
    ];

    // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
    packageNames.forEach(function (pkgName) {
        packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
    });

    var config = {
        map: map,
        packages: packages,
        meta: meta
    }

    // filterSystemConfig - index.html's chance to modify config before we register it.
    if (global.filterSystemConfig) { global.filterSystemConfig(config); }

    System.config(config);

})(this);

angularDep bundle
paths.documentRoot + "scripts/vendor/es6-shim/es6-shim.js",
paths.documentRoot + "scripts/vendor/zone.js/zone.js",
paths.documentRoot + "scripts/vendor/reflect-metadata/Reflect.js",

All bundles I have minified, but network trafic still look like this:

Thanks for your time.

A: Using systemjs-builder with Gulp you can bundle Angular 2 with your app code and bundle your other libraries separately.
I bundled any library I would reference directly in HTML into a vendors.min.js, and any library referenced through my system.config.js plus app code into an app.min.js. In this example you can see that all the dependencies in Tour of Heroes are loaded into the page in <10 network requests (source code).
gulpfile.js
// Bundle dependencies into vendors file
gulp.task('bundle:libs', function () {
    return gulp.src([
        'node_modules/jquery/dist/jquery.min.js',
        'node_modules/bootstrap/dist/js/bootstrap.min.js',
        'node_modules/semantic-ui/dist/semantic.min.js',
        'node_modules/es6-shim/es6-shim.min.js',
        'node_modules/es6-promise/dist/es6-promise.min.js',
        'node_modules/systemjs/dist/system.src.js',
        'system.config.js',
      ])
        .pipe(concat('vendors.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('public/lib/js'));
});

// Compile TypeScript to JS
gulp.task('compile:ts', function () {
  return gulp
    .src([
        "src/**/*.ts",
        "typings/*.d.ts"
    ])
    .pipe(tsc({
        "module": "system",
        "moduleResolution": "node",
        "outDir": "public/dist/js",
        "target": "ES5"
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('public/dist'));
});

// Generate systemjs-based builds
gulp.task('bundle:js', function() {
  var builder = new sysBuilder('public', './system.config.js');
  return builder.buildStatic('app', 'public/dist/js/app.min.js');
});

// Minify JS bundle
gulp.task('minify:js', function() {
  return gulp
    .src('public/dist/js/app.min.js')
    .pipe(uglify())
    .pipe(gulp.dest('public/dist/js'));
});

gulp.task('scripts', ['compile:ts', 'bundle:js', 'minify:js']);

system.config.js
// map tells the System loader where to look for things
var map = {
  'app':                                'dist/js',
  'rxjs':                               'lib/js/rxjs',
  'zonejs':                             'deps/zone.js/dist',
  'crypto':                             '@empty',
  'reflect-metadata':                   'lib/js/reflect-metadata',
  '@angular':                           'lib/js/@angular',
  'ng2-translate':                      'lib/js/ng2-translate',
  'angular2-infinite-scroll':           'lib/js/angular2-infinite-scroll',
  'lodash':                             'lib/js/lodash',
  'moment':                             'lib/js/moment',
  'angular2-moment':                    'lib/js/angular2-moment',
};

// packages tells the System loader how to load when no filename and/or no extension
var packages = {
  'app':                                { main: 'main', defaultExtension: 'js' },
  'rxjs':                               { defaultExtension: 'js' },
  'zonejs':                             { main: 'zone', defaultExtension: 'js' },
  'reflect-metadata':                   { main: 'Reflect', defaultExtension: 'js' },
  'moment':                             { main: 'moment', defaultExtension: 'js' },
  'angular2-moment':                    { main: 'index', defaultExtension: 'js' },
  'angular2-infinite-scroll':           { main: 'angular2-infinite-scroll', defaultExtension: 'js' },
  'lodash':                             { main: 'index', defaultExtension: 'js' },
  'ng2-translate':                      { main: 'ng2-translate', defaultExtension: 'js' },
};

var packageNames = [
  '@angular/common',
  '@angular/compiler',
  '@angular/core',
  '@angular/http',
  '@angular/platform-browser',
  '@angular/platform-browser-dynamic',
  '@angular/router',
  '@angular/router-deprecated',
  '@angular/testing',
  '@angular/upgrade',
];

// add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function(pkgName) {
  packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});

System.config({
  map: map,
  packages: packages
});


text:
Q: Chern numbers of primitive classes in BU How does one compute Chern numbers of spherical rational homology classes
$$f: S ^{2k} \to BU.$$ These generate rational homology by Milnor-Moore theorem since BU is a connected H-space, and so $c_k$ cannot kill such a class. It seems very likely that $\langle c_k,[f] \rangle =1$ but what is the proof?
Let me add here that I meant that $[f]$ is a Milnor-Moore generator, i.e. it's the multiplicative identity in $\pi_{2k} (BU, \mathbb{Q}) \simeq {\mathbb {Q}}$.

A: We have that if $f\colon S^{2k}\to BU$ is an actual map of topological spaces (it is a little bit unclear from your formulation if you assume this) then $\langle c_k,[f]\rangle>$ is a multiple of $(k-1)!$ and all multiple are possible. See for instance Husemoller: Fibre bundles, Cor 18.9.8, GTM 20, Springer Verlag.


text:
Q: Error occurred while connecting to SQL Server 2012: Cannot open user database. Login failed. (Microsoft SQL Server, Error: 4064) I unknowingly deleted SA user from the SQL Server 2012. Now i cannot be able to connect to the sever. It shows an error :
Cannot open user database. Login failed. Login failed for the user 'username'.(Microsoft SQL Server, Error: 4064)
Now i don't know what to do?
Help me please
Thanks

A: If you have Windows administator permissions, you can restart SQL Server in single-user mode. Any administrator can then log in locally and fix things.
Give this a shot as a place to start:
Connect to SQL Server When System Administrators Are Locked Out (MSDN)

A: When ever get this error,we have to create a new user with server authentication to connect the data base
We can create login for data base under security tab-->create new login under it


text:
Q: How to add a protected variable in java I need to add a protected variable to the product class file(i have attached the current code of that file) that i have. I need to change the access modifier for the count variable from public to protected.
How do i do that?! What changes i need to make in the code below to add a protected variable:
import java.text.NumberFormat;

public class Product
{
    private String code;
    private String description;
    private double price;
    public static int count = 0;

    public Product()
    {
        code = "";
        description = "";
        price = 0;
    }

    public void setCode(String code)
    {
        this.code = code;
    }

    public String getCode(){
        return code;
    }

    public void setDescription(String description)
    {
        this.description = description;
    }

    public String getDescription()
    {
        return description;
    }

    public void setPrice(double price)
    {
        this.price = price;
    }

    public double getPrice()
    {
        return price;
    }

    public String getFormattedPrice()
    {
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        return currency.format(price);
    }

    @Override
    public String toString()
    {
        return "Code:        " + code + "\n" +
               "Description: " + description + "\n" +
               "Price:       " + this.getFormattedPrice() + "\n";
    }

    public static int getCount()
    {
        return count;
    }
}

A: Just as you've declared count to be public, you can change it to be protected much in the same way just by using the protected keyword:
protected static int count = 0;

Note that this will prevent classes from other packages that do not extend Product from accessing count directly.  However, they will still be able to obtain its value from the getCount() method, as that is public.  If you wish to change that to be protected, you can do so again just by changing the keyword:
protected static int getCount()
{
    return count;
}

A: Your variables you have now:
private String code;
private String description;
private double price;
public static int count = 0;

If you want the count variable to be protected instead of public, it should be:
private String code;
private String description;
private double price;
protected static int count = 0;

A: try this
  public static void main(String[] args)
  {
     Product p=new Product();
     Class productClass = p.getClass();
     Field f = productClass.getDeclaredField("count");
     f.setAccessible(false); //Make the variable non-accessible
  }


text:
Q: Can a HKWorkoutBuilder object be used to collect workout data in an iPhone (with no paired Watch)? I am trying to figure out if I can use the HKWorkoutBuilder class on iPhone for workout data aggregation on the iPhone (for non-Watch users).
I watched the WWDC 2018 session number 707 New Ways to Work with Workouts, which introduces the new workout APIs. They demo it with the Watch, but make no mention of whether it can be used on the iPhone as well. HKWorkoutBuilder's documentation page on developer.apple.com mentions it being supported in both iOS and watchOS, as does the function beginCollection(withStart:completion:).
I have looked on the Net but can't find any tutorials or even any mention of it working on the iPhone alone. Or does it work on iOS as well, only so that Bluetooth-connected devices like Fitbit can provide the data?

A: Yes, it is. HKWorkoutBuilder's documentation page shows it is available on iOS 12+ and watch 5+
HKWorkout data is supported by HKSampleQuery which is used to query HealthKit data. So you should be able to get workout data on iOS without Watch.
Make sure data exits from other sources like apps/device and you have right permissions.


text:
Q: Какие использовать единицы для адаптивной вёрстки? Под конец запутался c применением единиц измерения в адаптивной вёрстке.
Кто-то на StackOverflow посоветовал всё прописывать в vh, но как выяснилось, это оказалось неверным решением.
Пожалуйста, подскажите по приложенному коду моей страницы где vh необходимо заменить на другие величины и почему.

@import url("/css/oblacheniya.css");
@import url("/css/oblacheniya-type-select.css");
@import url("/css/product-page.css");
@import url('https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz');

*, *:before, *:after {
  box-sizing: border-box;
}
html, body {
  height: 100%;
  padding: 0;
  margin: 0;
  background-color: #B63D32;
}
#page-wrapper {
  width: 100%;
  height: 100%;
}
#content-wrapper {
  width: 80%;
  height: 100%;
  display: inline-block;
  float: right;
}
header {
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: row;
  position: relative;
  border-top: 2vh solid black;
  border-left: 2vh solid black;
  border-right: 2vh solid black;
  border-bottom: 1vh solid black;
}
.container1 {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
}
.logo {
    width: 11.1vh;
    height: 11vh;
    padding-top: 0.8vh;
    padding-right: 11.5vh;
  }
.logo img {
    width: 11.3vh;
    height: 11vh;
    margin: 0vh auto;
    padding-top: 0vh;
}
.main_title {
    padding-top: 0.2vh;
    margin-left: 0vh;
    padding-right: 0vh;
    font-size: 4vh;
    font-family: ImpactI, sans-serif;
    color: #fff;
    text-shadow: 0vh 0.4vh rgba(0, 0, 0, .34);
    text-align: center;
}
.subtitle {
  font-size: 2vh;
  font-family: Lobster, sans-serif;
  letter-spacing: 0.14vh;
  font-weight: normal;
  color: #fff;
  text-align: center;
  margin-top: -0.3vh;
  padding-right: 0vh
}
.second_subtitle {
    font-size: 2.3vh;
    color: #000000;
    font-family: ImpactI, sans-serif;
    text-shadow: 0.1vh 0.05vh 0.3vh rgba(255,255,255,0.6);
    background-color: #666666;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    letter-spacing: -0.055vh;
    text-align: center;
    margin-top: -0.2vh;
}
.top_navigation-menu {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    margin-top: 1.5vh;
    text-align: center;
}
.top_navigation-menu li {
  width: 100%;
}
.top_navigation-menu a {
  text-decoration: none;
  color: white;
}
.top_navigation-menu li{
    display: block;
    margin: 0 auto;
    width: 100%;
    text-align: center;
}
.top_navigation-menu li a {
    color: white;
    text-decoration: none;
    font-size: 2.35vh;
    font-family: Courier New Cyr, sans-serif;
    font-weight: bolder;
}
.container1 ul {
  padding-bottom: 0vh;
  margin-bottom: 0vh;
}
.container1 ul li {
  padding-bottom: 0vh;
  margin-bottom: 0vh;
}
.container1 ul li>a:hover {
  color: black;
  transition: 0.4s;
}
main {
  width: 100%;
  height: 114vh;
}
/*ЛЕВОЕ МЕНЮ*/
/*ЛЕВОЕ МЕНЮ*/
.spisok {
  display: flex;
  justify-content: center;
  position: fixed;
  height: 100%;
  width: 20%;
  background-color: #7B2019;
  background-repeat: no-repeat;
  /*border*/
  border-top: 1.6vh solid black;
  border-bottom: 2vh solid #000;
  border-left: 1.5vh solid #000;
  border-right: 0vh solid #000;
  /*border ends*/
}
li {
  list-style-type: none;
}
.spisok li {
  width: 24vh;
  list-style-image: none;
  height: 5.5vh;
  background-image: url(/img/span_menu.png);
  background-size: 100% 100%;
  -webkit-background-size: 100% 100%;
  background-repeat: center no-repeat;
  transition: All 0.3s ease-in-out;
  margin-top: 0.45vh;
}

#oblacheniya {

}
.spisok li a {
  width: 100%;
  height: 100%;
  text-decoration: none;
  font-family: CyrillicOldBold, sans-serif;
  letter-spacing: 0.05vh;
  color: white;
  text-decoration: none;
  font-size: 2vh;
  font-weight: normal;
  }

.spisok ul>li:hover {
  background-image: url(/img/span_menu_hover.png);
  background-size: 100% 100%;
  -webkit-background-size: 100% 100%;
  background-repeat: center no-repeat;
  -webkit-transition: All 0.3s ease-in-out;
  -moz-transition: All 0.3s ease-in-out;
  -o-transition: All 0.3s ease-in-out;
  -ms-transition: All 0.3s ease-in-out;
  transition: All 0.3s ease-in-out;
}

.spisok ul li>a:hover {
  text-shadow: gold 0 0 4vh;
  /* Свечение голубого цвета */
  color: white;
}
ul {
  padding-left: 0vh;
}
.button.block {
  display: flex;
  justify-content: center;
  padding-left: 0vh;
}
.spisok ul {
  list-style-image: none;
  display: flex;
  justify-content: center;
  -webkit-flex-direction: column;
  -moz-flex-direction: column;
  -ms-flex-direction: column;
  -o-flex-direction: column;
  flex-direction: column;

}
.spisok ul li a p {
  display: flex;
  justify-content: center;
}

#ugol {
  background-image: url(/img/span_menu_black.png);
}

.text-div {
  width: 15.8vh;
  height: 3vh;
}

.letter-spacing {
  letter-spacing: 0.1vh;
}

.ryasi {
  letter-spacing: 0.2vh;
}
/*Начало SECTION*/
section {
  background: url(/img/fon.png);
  background-color: #BFBFBF;
  background-size: cover;
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  align-items: flex-start;
  width: 100%;
  height: 114vh;
  /*РАМКА*/
  border-left: 2vh solid black;
  border-top: 0vh solid black;
  border-right: 2vh solid black;
  border-bottom: 0vh solid black;
  /*Конец РАМКИ*/
}

.container2 {
  width: 100%;
  height: 109.9vh;
}

.Nashi_Tseny {
  width: 100%;
  height: 106.9vh;
}
.photo-price {
  height: 100vh;
}

.text-price {
  position: relative;
  margin: 0 auto;
  width: 100%;
  height: 98vh;
  border: solid transparent;
  border-width: 25vh 10vh 15vh 10vh;
  border-image: url(//i.stack.imgur.com/wky2z.png);
  border-image-slice: 800 250 338;
  border-image-repeat: round;
}
.text-price {
  font-size: 2.3vh;
  font-family: Yanone Kaffeesatz, sans-serif;
  font-style: normal;
  text-decoration-skip-ink:none;
}

.text-price p {
  padding-left: 2vh;
}
#first_abzac {
  margin-top: -2vh;
}
.photo-price {
  height: 97vh;
  width: 100%;
}
.border-price {
  max-width: 10vh;
}
.choose_otstup {
 margin-left: 1vh;
}
h2 {
  margin-top: 3vh;
  font-size: 4.7vh;
  font-family: ImpactI;
  font-weight: 400;
  padding-top: 0.5vh;
  text-decoration: underline;
  text-decoration-skip-ink:none;
  text-align: center;

}

strong {
  font-weight: bolder;
  font-size: 2.1vh;
}

.vosem_tis {
  font-style: italic;
  font-weight: 900;
  font-family: Lobster, sans-serif;
  font-size: 1.9vh;
}
/*НАЧАЛО FOOTER*/
footer {
  width: 100%;
  height: 15vh;
  border-left: 2vh solid black;
  border-right: 2vh solid black;;
  border-top: 1vh solid black;;
  border-bottom: 2vh solid black;;
}
/*КОНЕЦ FOOTER*/
<?php
 require_once $_SERVER['DOCUMENT_ROOT'].'/objects/head.php';
?>

       "ШвейПокров"

        Православная швейная мастерская

       доставка по всей России

Главная

Контакты

О нас

Наши цены:

Облачения:

-иерейские шелковые от 9000   рублей с шикарными галунами

-иерейские парчевые от 10000  рублей*

Подрясники:

Подризники:

Рясы:

Стихари:

Скуфии: от 800 рублей;

Камилавки: от 1700

Крещальные:

Облачения для храма:

Вышитые кресты:

Кадильный уголь:

*парчевые облачения с индийскими галунами шьются по заказу

<?php
 require_once $_SERVER['DOCUMENT_ROOT'].'/objects/footer.php';
?>


text:
Q: How to connect values inside two RefCells Sample code :
use serde_json::{json, Value};

fn main() {
  let a: Rc<RefCell<Value>> = Rc::new(RefCell::new(json!({"a": "value"})));
  let v: Rc<RefCell<Vec<Value>>> = Rc::new(RefCell::new(vec![]));

  // How to push a into v, but keep `a` and `v` for future uses
}

I want to push Value a into vector v (link pointer), but still be able to use a later on.
I've tried the following:
1.
v.borrow_mut().push(*a.borrow_mut());

This does not work, as Value does not implement Copy trait, thus could not be dereferenced
2.
v.borrow_mut().push(RefCell::take(&a));

This works, however a has now lost the contents. I do understand that there should only be one owner, but I'm not sure how to achieve what I need.
The Why
I have a Value which I need to modify depending on some other data which is in a tree structure. I want to recursively walk through that other data tree, and pass along this Value to be modified.
In my function, I have this Value signature as Rc<RefCell<Value>>, and depending on the case I sometimes need to add nested properties, so I may need to add a property containing a vector with a new json!({}), and pass it as a new Rc<RefCell<Value>> to sub-iterations to append data to this specific subtree.
So, if you have any advice - maybe I need to change the recursive function's signature to have this data as Rc<RefCell<&Value>> instead, to have only one owner ? That seems like an awful lot of all sorts of references stacked upon one another, not sure which is the good way
Edit1: Updated sample to include Rc<RefCell<_>>


text:
Q: Error using the with clause I received message " Syntax error: Expected keyword AS but got "(" at [7:14]" I am having an issue locating the error in my code
I am practicing the WITH CLAUSE IN Big Query and I am trying to create two temporary tables to eventually join

*

*first table would for the sum total sales from all the stores (grouping by storeid)

*second table would be to get the average of those sum total stores

*the main query would be to find which stores are greater than the average sum total store

here is what I was able to code:
WITH Total_sales as
    (SELECT s.storeid,
            sum(Unitprice)as sum_sale
            FROM `g-mail-1234.SALES.sales_info` as s
            GROUP BY storeid),

    AVG_Sale (average_s_sales) as
    (SELECT ROUND(avg(sum_sale),2) as average_s_sales
      FROM total_sales)

    SELECT * FROM total_sales as ts
    JOIN avg_sale as av
    ON ts.sum_sale > av.average_s_sale

but when I run the code I get a message:
Syntax error: Expected keyword AS but got "(" at [7:14]
what I would like to know is:

*

*Where is the error?

*In the future in BigQuery the 'at [7:14]' is this trying to tell me the line the error code is on? because it is on neither line 7 or line 14

A: I don't believe BQ CTE syntax allows you to list the columns that the CTE will return. So this line:
    AVG_Sale (average_s_sales) as

should just be:
    AVG_Sale as


text:
Q: Error in NUnit Console: "WaitAll for multiple handles on a STA thread is not supported" Similar to this question, I upgraded to version 2.6 of NUnit, and started getting a threading error.

WaitAll for multiple handles on a STA thread is not supported

The tests run fine under the NUnit GUI, but fail on the console version.

A: I guess the new NUnit console version must have switched from multi-threaded apartment model to single-threaded. Anyway, there's a command-line switch to set it back to MTA. Here's the relevant section from my NAnt build script.
<exec program="nunit-console.exe" if="${nunit-in-path}">
  <arg file="../ZaberConsole/ZaberConsoleTest.nunit"/>
  <arg value="/apartment=MTA"/>
</exec>

A: Alternatively try setting the RequiresMTA attribute on the assembly.
This worked for me.


text:
Q: Spring: Register a component within a test class I am registering an ErrorHandler for my Spring Scheduler and would like to test that is is correctly registered in a SpringTest
So far I have tried:
Handler
@Component
public class ScheduledErrorHandler implements ErrorHandler {
    @Autowired
    private ErrorService errorService;

    @Override
    public void handleError(final Throwable t) {
        errorService.handle(t);
    }

}

Registering the Handler
@EnableScheduling
@Configuration
public class SchedulingConfiguration implements SchedulingConfigurer {

    @Autowired
    private ScheduledErrorHandler handler;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(1);
        scheduler.setErrorHandler(handler);
        scheduler.initialize();
        taskRegistrar.setScheduler(scheduler);
    }

    //...
}

Testing it's registered
@ContextConfiguration(classes = {
    SchedulerConfiguration.class,
    SchedulerErrorHandler.class
})
@RunWith(SpringRunner.class)
public class SchedulerErrorHandlerTest {

    @MockBean
    private ErrorService service;

    @Autowired
    private ExampleScheduledJob job;

    @Test
    public void verifyHandlerGetsCalled() {
        // Wait until the job runs
        if(!job.latch.await(5, SECONDS)) {
            fail("Job never ran");
        }

        verify(service).handle(any(RuntimeException.class));
    }

    @Component
    public static class ExampleScheduledJob {
        private final CountDownLatch latch = new CountDownLatch(1);

        @Scheduled(fixedRate=1000)
        public void run() {
            latch.countDown();
            throw new RuntimeException("error");
        }
    }
}

However when I do this I get a DependencyNotFound error saying Spring cannot create my test class as no Bean named ExampleScheduledJob can be found. How can I register it only for the sake of this test?

Error creating bean with name
  'com.example.demo.SchedulerErrorHandlerTest': Unsatisfied dependency
  expressed through field 'job'; nested exception is
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type
  'com.example.demo.SchedulerErrorHandlerTest$ExampleScheduledJob'
  available: expected at least 1 bean which qualifies as autowire
  candidate. Dependency annotations:
  {@org.springframework.beans.factory.annotation.Autowired(required=true)}

A: This should work
@ContextConfiguration(classes = {
        SchedulingConfiguration.class,
        SchedulerErrorHandlerTest.ExampleScheduledJob.class,
        ScheduledErrorHandler.class
})
@RunWith(SpringRunner.class)

You can register your test configuration class (ExampleScheduledJob) as indicated above. Since it is a static inner class, you need to use it like SchedulerErrorHandlerTest.ExampleScheduledJob


text:
Q: How to create an array from the keys of an associative array? I have an associative array:
declare -A hash

hash[one]=1
hash[two]=2
hash[third item]=3

How can I create an indexed array from the keys of this associative array?

A: To make an array with the keys from an associative array:
arr=("${!hash[@]}")

To make an array with the values:
arr=("${hash[@]}")

Note that you need the double quotes to prevent the shell from word splitting.


text:
Q: How to connect 3 dots with 2 line segments when the dots come from different cells of GraphicsGrid? I want

*

*to connect the 3 red dots

*to make the red dots depicted on the sinusoidal circular rather than elliptical.

*to make these 3 canvas are properly scaled such that joining lines are parallel to horizontal and vertical axes.

Manipulate[
 GraphicsGrid[{
   {
    Graphics[{
      {Red, Disk[{Cos[t], Sin[t]}, 0.05]},
      {Dashed, Blue, Line[{{0, 0}, {Cos[t], Sin[t]}}]},
      {Dashed, Gray, Circle[{0, 0}, 1]}
      }, PlotRange -> {{-1.2, 1.2}, {-1.2, 1.2}}, Axes -> True,
     AspectRatio -> 1],
    Show[
     Graphics[{
       {Red, Dashed, Line[{{t, 0}, {t, Sin[t]}}]},
       {Red, Dashed, Line[{{0, Sin[t]}, {t, Sin[t]}}]},
       {Red, Disk[{t, Sin[t]}, 0.09]}
       }],
     Plot[Sin[x], {x, 0, t}]
     , PlotRange -> {{-0, 2 \[Pi]}, {-1.2, 1.2}}, Axes -> True,
     AspectRatio -> 1, AxesLabel -> {"t", "Sin[t]"}]
    }, {
    Rotate[Show[
      Graphics[{
        {Red, Dashed, Line[{{t, 0}, {t, Cos[t]}}]},
        {Red, Dashed, Line[{{0, Cos[t]}, {t, Cos[t]}}]},
        {Red, Disk[{t, Cos[t]}, 0.09]}
        }],
      Plot[Cos[x], {x, 0, t}]
      , PlotRange -> {{-0, 2 \[Pi]}, {-1.2, 1.2}}, Axes -> True,
      AspectRatio -> 1, AxesLabel -> {"t", "Cos[t]"}], -\[Pi]/2]
    }
   }],
 {t, 0.001, 2 \[Pi]}]

A:
Q2. To prevent disks from appearing as ellipses you can

*

*Specify the radius as Offset[r] in absolute units. That is,

 {Red, Disk[{t, Cos[t]}, Offset[4]]}

and
 {Red, Disk[{t, Sin[t]}, Offset[4]]}

*Use Point instead of Disk: e.g.,

 {Red, AbsolutePointSize[7], Point[{t, Sin[t]}]}

Q3: Use the same ImageSize in all three plots (adding invisible axes labels where missing to prevent different automatic resizing caused by different sized labels)
Q1: It may be possible to do it without abandoning GraphicsGrid ... but an alternative approach using a single plot with all the desired elements is possible:
Without the axes we can get the three plots in a single ParametricPlot:
Manipulate[ParametricPlot[{{Cos[x], Sin[x]}, {2 + x, Sin[x]}, {Cos[x], -2 - x}},
   {x, 0, t},
   MeshFunctions -> {#3 &},
   Mesh -> {{t}},
   MeshStyle -> Directive[Red, PointSize[Large]],
   PlotStyle -> Thick,
   PlotRange -> {{-3/2, 2 + 2 Pi}, {-2 - 2 Pi, 3/2}},
   Axes -> False,
   ImageSize -> 300,
   PlotRangePadding -> Scaled[.03],
   ImagePadding -> 20,
   PlotRangeClipping -> False,
   Prolog -> {Thick, Dashed, Green, Line[{{0, 0}, {Cos[t], Sin[t]}}],
     EdgeForm[Dashed], FaceForm[Opacity[.2, Yellow]],
      Polygon[{{Cos[t], Sin[t]}, {2 + t, Sin[t]}, {Cos[t], -2 - t}}]}],
 {{t, Pi/3}, 0.01, 2 Pi}]

To add the three axes we need to construct graphics primitives that look like axes:
ClearAll[axisFunc]
axisFunc[tl1_: 5, tl2_: 5, to_: - 25][a_, b_, start_, end_, z_,
   dir : (Horizontal | Vertical)] :=
  Module[{f = dir /. {Horizontal -> Identity, Vertical -> Reverse},
     p = dir /. {Horizontal -> 1, Vertical -> 2}},
  {Text[Style[#[[p]] If[a < b, 1, -1], 10], Offset[f@{0, to/p},
     MapAt[Rescale[#, {a, b}, {a + start, b + end}] &, #, {p}]], {0, 0}] & /@
     (If[tl1 > 0 && tl2 > 0, Rest@#, #] &@ Thread[f@{Subdivide[a, b, 3], z}]),
    Thin, Line[{f@{#, z}, f@{#2, z}}] & @@ {a + start, b + end},
    Line[{Offset[f@{0, -tl1}, #], Offset[f@{0, tl2}, #]}] & /@
     Thread[f@{Subdivide[a + start, b + end, 3], z}],
    Line[{Offset[f@{0, -tl1/2}, #], Offset[f@{0, tl2/2}, #]}] & /@
     Thread[f@{Complement[Subdivide[a + start, b + end, 9],
         Subdivide[a + start, b + end, 3]], z}]}];

We use axisFunc with different parameters to construct the axes to be added to the Prolog option setting:
axes = {axisFunc[5, 5, -10][0, 2 Pi, 2, 2, 0, Horizontal],
   axisFunc[10, 0, 10][-1, 1, 0, 0, -2, Horizontal],
   axisFunc[][0, -2 Pi, -2, -2, 0, Vertical],
   axisFunc[0, 10, -15][-1, 1, 0, 0, 2, Vertical]};

axeslabels = {Text[Style[TraditionalForm[Sin[θ]], 15, Black], {1.4, 0}, {0, 0}, {0, 1}],
   Text[Style[TraditionalForm[Cos[θ]], 15, Black], {0, -1.4}, {0, 0}],
   Text[Style[TraditionalForm[θ], 15, Black], {2.3 + 2 Pi,  0}, {0, 0}],
   Text[Style[TraditionalForm[θ], 15, Black], {0, -2.3 - 2 Pi}, {0, 0}]};

Manipulate[ParametricPlot[{{Cos[x], Sin[x]}, {2 + x, Sin[x]}, {Cos[x], -2 - x}},
  {x, 0, t},
  MeshFunctions -> {#3 &},
  Mesh -> {{t}},
  MeshStyle -> Directive[Red, PointSize[Large]],
  PlotStyle -> Thick,
  PlotRange -> {{-3/2, 2 + 2 Pi}, {-2 - 2 Pi, 3/2}},
  Axes -> False,
  ImageSize -> 400,
  PlotRangePadding -> Scaled[.03],
  ImagePadding -> 20,
  PlotRangeClipping -> False,
  Prolog -> {axes, axeslabels, Dashed, Thick, Red,
    Line[{{0, -2 - t}, {Cos[t], -2 - t}}], Line[{{2 + t, Sin[t]}, {2 + t, 0}}],
    Green, Line[{{0, 0}, {Cos[t], Sin[t]}}], EdgeForm[Dashed],
    FaceForm[Opacity[.2, Yellow]],
    Polygon[{{Cos[t], Sin[t]}, {2 + t, Sin[t]}, {Cos[t], -2 - t}}]}],
 {{t, Pi/3}, 0.01, 2 Pi}]

Replace Manipulate[stuff, {{t, Pi/3}, 0.01, 2 Pi}] with
frames = Table[stuff, {t,  0.01, 2 Pi, 2 Pi/100}];

and Export frames as GIF file to get the animation at the top.


text:
Q: Is posible build an indoor localization system with android device inertial sensors I'm working on an indoor positioning system and I have one doubt after failing at all my real tests:
I have done some work with android sensors values and some machine learning algorithms (with good theorical results) but in a real environement i found some problems.
My proposal was to have three phases:

*

*The fist phase consist on collecting data through an android app with a map with some points. You move to real point position and save the values of sensors asociated with the coordinates of the point.

*The second phase consist on creating a machine learning model (in this case, a classifier) to predict the user position based on sensor values at every time.

*Then, we export the classifier to the device and get predictions of user position in real time.

The data we stored on fingerprinting phase (phase 1) was the x,y,z values of accelerometer, magnetomer and gyroscope given by the Android Sensor Manager. On a second approach, we used a median filter to filtrate noise from that values. Our problem is that the way you hold the phone change the measurements. The reason is that Android sensors values are given for device coordinate system, so sensor values are variable to phone orientation and tilt.
Android Device Coordinate System
So, the question is:
Is posible or there is a way to build an indoor localization system (with a positioning accuracy around 2-3 meters) by only taking in account android smartphone sensors (accelerometer, gyroscope and magnetomer) using machine learning algorithms (or other algorithms) to work on real environements?
Thanks in advance!!

A: There are a few companies that started doing fingerprinting solely based on magnetometer, but as far as I know they ended up at least mixing it with other technologies, like BLE beacons or similar.
From what I was told the problem is that magnetic fields can change drastically due to changes inside your building but also changes outside of your scope (i.e. thunderstorms).
Taking one step back I see another problem with your approach: different device models behave radically different in terms of the data their sensors provide. To make things worse, the same device may provide very different data today than it did yesterday. This is especially true for the magnetometer - at least from my experience.


text:
Q: Chrome Custom Tabs redirect to Android app will close the app I am trying to implement an OAuth2 flow with an Android Chrome Custom Tab but my app is always closed (no crash) when the Chrome Custom Tab is receiving the 302 with the location/scheme  of my app.
If I create a HTML page with ahref link and touch manually on it the Chrome Custom Tab is correctly switching to my app.
Seems like when handling the server 302 redirect in the Chrome Custom Tab it will not correctly handle my custom app scheme... but why?
If I try the same redirect URL in a stock browser or with a WebView everything is working too.
Here is my current setup:
MainActiviy.java
    Button btnChromeCustomTab = (Button) findViewById(R.id.btnChromeCustomTab);
    btnChromeCustomTab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build();
            String packageName = CustomTabsHelper.getPackageNameToUse(MainActivity.this);
            customTabsIntent.intent.setPackage(packageName);
            Uri theLocationUri = Uri.parse(URL);
            customTabsIntent.launchUrl(MainActivity.this, theLocationUri);
        }
    });

AndroidManifest.xml
    <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter android:label="@string/filter_title">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="myappscheme" android:host="oauth" />
        </intent-filter>
    </activity>

This is the redirect URL that the app received with HTTP 302 code:
myappscheme://oauth?code=1234567&state=tokenCheck123
build.gradle
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "de.myapptest.webviewtest"
    minSdkVersion 16
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   testCompile 'junit:junit:4.12'
   compile 'com.android.support:appcompat-v7:23.2.1'
   compile 'com.android.support:design:23.2.1'
   compile 'com.android.support:customtabs:23.0.0+'
}

Thanks for any help...

A: If I used android:launchMode="singleInstance" there were multiple instances in the task manager so this was no option.
Starting the CustomTabsIntent with FLAG_ACTIVITY_NEW_TASK Flag did the trick.
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent intent = builder.build();

intent.intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
intent.launchUrl(context, Uri.parse(url));

A: I've also observed my Android app unexpectedly background after server-side 302 redirection to a custom scheme, and observed expected handling from stand-alone Chrome and manually triggered redirection in the client.
I was able to "fix" the issue by calling the warmup function before loading the url that redirects.
In other words, this works:
void launchTab(Context context, Uri uri){
    final CustomTabsServiceConnection connection = new CustomTabsServiceConnection() {
        @Override
        public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient client) {
            final CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
            final CustomTabsIntent intent = builder.build();
            client.warmup(0L); // This prevents backgrounding after redirection
            intent.launchUrl(context, uri);
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {}
    };
    CustomTabsClient.bindCustomTabsService(context, "com.android.chrome", connection);
}

This doesn't work:
void launchTab(Context context, Uri uri){
    final CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
    final CustomTabsIntent intent = builder.build();
    intent.launchUrl(context, uri);
}

The Chrome Custom Tab docs describe warming up as a best practice, but it also appears to help ensure expected behavior.
In terms of env, I'm testing on a Nexus 5X w Chrome 51. My chrome tab dependency in Gradle looks like this:
dependencies {
    compile 'com.android.support:customtabs:24.0.0'

A: It helped me to set the Activity that I use to start a CustomTab to singleInstance mode in the  manifest file:
    <activity
        android:launchMode="singleInstance"
        android:name="com.example.SingleInstanceActivityToStartCustomTab"
    </activity>

And in the code I do as usual:
    CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
    final CustomTabsIntent customTabsIntent = builder.build();
    customTabsIntent.intent.setPackage(someChromePackage);
    customTabsIntent.launchUrl(singleInstanceModeActivity, someUriThatDoesRedirect);

I tried warming up Chrome and even calling customTabsIntent.launchUrl() with some delay after calling client.warmup(0l); and neither helped.

A: I'm pretty sure this is the result of a bug in Chrome.  I updated all of my devices (GS6, GS7, Nexus 7 and Nexus 9) to the latest version of Chrome and my app is no longer minimized when the redirect occurs.
I just discovered this today (11/3/2016) so I don't yet have any information about the specific bug or its subsequent resolution.  This is just what I've noticed.
Hope that helps!


text:
Q: how to add numbers in numeric string in perl I am facing some problem while adding values in numeric string:
I have string that looks like 02:03:05:07:04:06. All the numbers have to be <10. Now, I have to take a random number from 1-9  and add that number with last position number of the string (e.g. 3).
I the sum>10, then I have add that number to the number in the second last position.
So far, I have
#!/usr/bin/perl -w
use strict;
my $str='02:03:05:07:04:06';
my @arr=split(/:/,$str);
my @new_arr=pop(@arr);
my $rand_val=int(rand(9));
my $val=$new_arr[0]+$rand_val;
if($val>=10)
{
   I am unable to generate a logic here:(

}

Please help me out of this problem.
After adding the number we have to join the string and print it also :)

A: my $str = '02:03:05:07:04:06';
my @nums = split /:/, $str;
my $add = int(rand(9)) + 1;
my $overflow = 1;
for (1..@nums) {
   if ($num[-$_] + $add < 10) {
      $num[-$_] += $add;
      $overflow = 0;
      last;
   }
}

die "Overflow" if $overflow;

$str = join ':', map sprintf('%02d', $_), @nums;

A: I just run this and it works. The caveat is that, the lower the last number of the string is, the smaller the chance the "if ($val>=10)" will be valid

A: This doesn't solve the problem of your rand_val potentially being 0, but I'll leave that as a task for you to resolve.  This should give you what you're looking for in terms of traversing through the values in the array until the the sum of the random value and current most-last value in the array.
1  use strict;
2  my $str='02:03:05:07:04:06';
3  my @arr=split(/:/,$str);
4  my $rand_val=int(rand(9));
5  my $val;
6
7  foreach my $i (reverse @arr){
8    $val = $i + $rand_val;
9    next if ($val >= 10);
10   print "val: $val, rand_val: $rand_val, value_used: $i\n";
11   last if ($val < 10);
12 }

A: I see a misstake : you do
my @new_arr=pop(@arr);
(...)
my $val=$new_arr[0]+$rand_val;

but pop only returns the last element, not a list.