text:
Q: How to set Up XAMPP/Apache to make internet work behind the firewall I got a machine running XAMPP and two browsers, chrome and firefox. The structure of the network is:
LAN > Firewall > DMZ > Router > Internet > Registered Domain > database

I use Chrome for internet access, currently setup to pass the firewall. Meaning to say the config is like, the proxy would be the firewall and gateway will be my internet router. Firefox on the other hand has "no proxy" settings so it does not go out the net because it's blocked by firewall, but I'll be able to view pages on my Apache server via XAMPP running on my local machine and/or LAN.
Here is where it get's tricky: The PHP pages I got needs to run on Apache server via XAMPP but content is pulled at a registered domain database outside the internet.
So the problem is, if I run my php page from Firefox, I can see my page but the content  I'm trying to get from the internet is being blocked by the firewall. If I run the page from the Chrome, the proxy passes my connection outside the net where my XAMPP is not present so normally I get an error saying content not available. I need to find a way to make XAMPP working and host my page while it gets it's data from the Registered Domain
Any ideas how to solve this? I do not want to change any setting on my firewall or router, I was thinking about config of XAMPP or Apache that can do forwarding to outside proxy when content is not present. If my idea is valid, how do I do this?
What I've done so far:
1.) Right now I transferred my pc outside the firewall (connected via router)... it works fine so meaning if I put it back behind the firewall, I just need to configure something in XAMPP or Apache. That is what I'm looking for.
2.) I also tried swapping setting on Chrome and Firefox. Same problem, only reversed.
3.) I've also played around with the httpd-proxy.conf as suggested in the net but nothing is working for me. I do not understand Apache that much to be able to configure it properly.
4.) On another network where the structure is like:
PC >Router > Internet > Registered Domain > database

... my page displays fine with data displaying as it should.
5.) I tried using Chrome with proxy setup (with internet) after setting a virtual host but it did not work. It did not display the page and same error i get from chrome. Here is my setup.
<VirtualHost *:80>
    ServerAdmin myname@gmail.com
    DocumentRoot "C:/xampp/htdocs"
    ServerName <IP address of my PC>
    ServerAlias <IP address of my PC>
    ##ErrorLog "logs/dummy-host.example.com-error.log"
    ##CustomLog "logs/dummy-host.example.com-access.log" common
</VirtualHost>

the error is:
Network Access Message: The page cannot be displayed
Explanation: There is a problem with the page you are trying
  to reach and it cannot be displayed.
Try the following:
Refresh page: Search for the page again by clicking the Refresh button.
The timeout may    have occurred due to Internet congestion.
Check spelling: Check that you typed the Web page address correctly.
The address may have been mistyped.
Access from a link: If there is a link to the page you are looking for,
try accessing the page from that link.
If you are still not able to view the requested page, try contacting your
administrator or Helpdesk.
Technical Information (for support personnel)
Error Code: 502 Proxy Error. The ISA Server denied the specified Uniform Resource Locator (URL). (12202)
IP Address: (IP address of firewall)
Date: (12/9/2013 11:48:43 PM)
Server: (myFirewallServer)
Source: proxy
6.) I tried configuring the Chrome's Proxy setting to make my IP address as an exception. It displayed the page but not the data. Same error as that with Firefox.
PHP program are as follows: I've replaced some contents for my protection.
  ...
  <?php
      // Create connection
      $con=mysqli_connect(...);

      // Check connection
      if (mysqli_connect_errno())
        {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

      $result = mysqli_query($con,"SELECT ... where ... " );

      while($row1 = mysqli_fetch_array($result))
        {
          $rowAA = $row1['Field1'];
          $rowBB = $row1['Field2'];
        }
  ?>

  ...

  <?php   echo $rowAA;   ?>

  ...

   <?php   echo $rowBB;   ?>

  ...


text:
Q: How to backwards search in Xcode 4? I cannot figure out how I can use reverse find in Xcode 4. Back in Xcode 3 I simply used CMD + F and then RETURN to search forwards and SHIFT + RETURN to search backwards. The latter shortcut combinination is no longer working in Xcode 4, though. That suckz!
I am currently using Xcode 4.2.

A: Once you've found a match, use Command-G to find the next one, and Shift-Commmand-G to find the previous one. If you prefer some other shortcuts, feel free to modify the key bindings in Xcode's preferences. From the key bindings panel:

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use ZAP to scan web application hosted in embedded browser control I have a web application (developed in Angular4) hosted with embedded web browser that is Chromium Web Browser Control (CefSharp) in a desktop application.
The web application is tightly coupled with host desktop application hence cannot be run it on browser independently.
Considering the scenario, Can I automate scanning or by any means perform scanning manually with ZAP API tool ?

A: After spending few minutes I realized that ZAP is independent of browser type. It  supports any type of browser (including embedded one).
What it needs to read websites  is proxy set up.
I just set up proxy to "CefSettings" while initializing the app.
Note: ZAP server is running on "localhost:8081".
var cfsettings = new CefSettings();
cfsettings.CefCommandLineArgs.Add("proxy-server", "localhost:8081");

Cef.Initialize(cfsettings);
browser = new ChromiumWebBrowser();


text:
Q: Yesod - function for getting the value of an Entity take a look:
myEntity :: Entity Post
myEntity = ...

myValue :: Entity Post -> Post
myValue = <someFunction>

myKey :: Entity Post -> PostId
myKey = <someOtherFunction>

Does someFunction and someOtherFunction exist in yesod or do I need to create them?

A: You have Entity key val, then for val
> :t entityVal
entityVal :: Entity record -> record
> :i entityVal
type role Entity nominal
data Entity record where
  Entity :: PersistEntity record =>
            (Key record) -> record -> Entity record
        -- Defined in 'persistent-2.2.1:Database.Persist.Class.PersistEntity'

or for key
> :t entityKey
entityKey :: Entity record -> Key record
> :i entityKey
type role Entity nominal
data Entity record where
  Entity :: PersistEntity record =>
            (Key record) -> record -> Entity record
        -- Defined in 'persistent-2.2.1:Database.Persist.Class.PersistEntity'

or for both you can use pattern matching, e.g.
> let getR (Entity k v) = (k , v)
> :t getR
getR :: Entity t -> (Key t, t)


text:
Q: Yii will not move_uploaded_file - 500 internal server error I'm using the blueimp File Upload Plugin with Yii to try and upload a file to my server (currently localhost). I gave the folder full read / write permissions (the location is C:\xampp\htdocs\yii), but I still get an error when I try to do the move_uploaded file command.
Here is the main form and input file area:
<form id='upload' method='post' action='?r=site/move' enctype='multipart/form-data' style="padding:0;">
    <span class="btn fileinput-button" style="padding:0">
        <i class="glyphicon glyphicon-picture">
            <input id="fileupload" type="file" accept="image/*" name="attachment" onchange="attachAttachment()">
        </i>
    </span>
</form>

Here is blueimp's fileupload (in function()):
$("#fileupload").fileupload
({

        dataType: 'json',

        done: function (e, data)
        {
            console.log("YAY");
        },

        fail: function(e, data)
        {
            console.log("FAIL");
        }
});

Here is the actionMove, where I move the file from the temp directory to the folder:
public function actionMove()
{
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0)
    {
        if (move_uploaded_file($_FILES['attachment'], Yii::getPathOfAlias('webroot')."/images/uploads")){
            $response = '{"status":"success"}';
        }
        else {
            $response = '{"status":"error"}';
        }

        echo $response;
        exit();
    }
}

I have been at this for hours now, any help is appreciated :(

A: $_FILES['attachment'] references all data about the download. move_uploaded_file uses filenames to work. Here is what you should try:
$uploadPath = Yii::getPathOfAlias('webroot')."/images/uploads";
$uploadFilename = basename($_FILES['attachment']['name']);
$tempFilename = $_FILES['attachment']['tmp_name'];
$ok = move_uploaded_file($tempFilename, $uploadPath.'/'.$uploadFilename);
if ($ok) {
    $response = '{"status":"success"}';
} else {
    $response = '{"status":"error"}';
}

More on this on the documentation pages:
http://php.net/manual/fr/features.file-upload.post-method.php
and
http://php.net/manual/fr/function.move-uploaded-file.php
Hope it helps.


text:
Q: Characterizing optimal points in a linear program Suppose I have a linear program of the form
$$ \max c^T x $$
$$ Ax \le  b$$
And some mystical oracle gives me a  point $x'$ claiming it is an optimal solution.
How could I determine if this is true, without solving the linear program from scratch.
Now perhaps it is easier if we know ahead of time there is a unique max. Then we can test if $x'$ is an extreme point, and perhaps try to compute all its adjacent vertices and verify it has maximal objective value over them. But this leads to three questions:

*

*I said that algorithm at a high level, how do I actually do that?

*What if we relax the condition to perhaps a non unique max, then we lose out on the extreme point tests etc...

*Is there an algebraic characterization we can do instead? If I wanted to state all optimal $x'$ satisfy some $f(x',A,c^T,b) = 0$ what would that property be?
The last point (#3) I'm most interested in. I'm curious if we can do an approach involving lagrange multipliers with the inequalities that are tight for the value $x'$ to reason, that there is no direction one can walk that is better. This would be useful for example in proofs where we say
Given $x'$ is optimal prove some statement $\phi(x',A,b,c^T)$.
Then knowing this property of $x'$ gives you an equation to work with to manipulate to conclude $\phi$

A: Look for KKT conditions for a linear program.
The terminology used for such conditions is certificate of optimality.
I would suggest to check one of main references about optimality certificate, such as in Boyd and vandenberghe book.
See also theorem 4.2.2 of Introduction to optimization lecture notes 4 on LP, where it states:
Theorem 4.2.2. (Certificate of Optimality) If $x$ and $y$ are feasible solutions of the primal and dual and $c^\top x = b^\top y$, then $x$ and $y$ must be optimal solutions to the primal and dual.

A: First check if this point $x'$ is a vertex. Then do perturbation by adjusting x about that point and check to see if it is the optimal point.


text:
Q: Unit Testing Login Vue Jest ValidationProvider I am new to Jest and I am trying to mock the store, an action and to assert that the method was indeed called. Basically I want to check the login function.

*

*I cannot query the button because I am retrieving only a part of the component and I don't know what I'm missing.

Where my Vue component looks like:

<ValidationObserver id="observer" v-slot="{ invalid }" :class="['w-full h-full']">
  <form class="flex flex-col justify-around h-full" @submit.prevent="onSubmit">
    <ValidationProvider v-slot="{ errors }" name="accessCode" :class="['w-full py-6']">
      <sd-field :class="['sd-field_secondary', { ['sd-invalid ']: errors && errors.length > 0 }]">
        {{ $t("form.access-code") }}
        <sd-input v-model="accessCode" type="accessCode" />
        {{ errors[0] }}
      </sd-field>
    </ValidationProvider>

      <button class="btn btn-fixed btn-blueDark" type="submit">
        {{ $t("account.login") }}
      </button>

  </form>
</ValidationObserver>

 ***MY TEST FILE***
import login from "../../pages/index/login";
import Vuex from "vuex";
import { mount, createLocalVue } from "@vue/test-utils";
const localVue = createLocalVue();
localVue.use(Vuex);

describe("Login form", () => {
  it("calls the login action correctly", () => {
    const loginMock = jest.fn(() => Promise.resolve());
    const store = new Vuex.Store({
      actions: {
        onSubmit: loginMock,
      },
    });
    const wrapper = mount(login, { localVue, store, stubs: { ValidationObserver: true } });
    console.log(wrapper.html());
   // wrapper.find("button").trigger("click");
  // expect(loginMock).toHaveBeenCalled();
  });
});

console.log(wrapper.html()) returns only a part of component

<validationobserver id="observer"
    class="w-full h-full"> </validationobserver>

With a warning also:
> console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
>         [Vue warn]: Unknown custom element: <ValidationObserver> - did you register the
>         component correctly? For recursive components, make sure to provide the "name" option.
>         found in
>        ---> <Anonymous>
>            <Root>

I would like to understand how this works, I have tried to stub and other ways found but with no success.
I can get rid of the warning by adding the stubs: { ValidationObserver: true } to mount but I actually need to access the elements inside.
Thank you!


text:
Q: Pandas transform: assign result to each element of group I am currently using pandas groupby and transform to calculate smth for each group (once) and then assign the result to each row of the group.
If the result of calculations is scalar it can be obtained like:
df['some_col'] = df.groupby('id')['some_col'].transform(lambda x:process(x))

The problem is that the result of my calculations is vector, and pd tries to make element-wise assignment of result vector to the group (quote from pandas docs):

The transform function must:
  Return a result that is either the same size as the group chunk or broadcastable to the size of the group chunk (e.g., a scalar, grouped.transform(lambda x: x.iloc[-1])).

I could hardcode external function, creating a group-sized list, that will contain copies of result  (currently on python 3.6, so it's not possible to use assignment inside lambda):
def return_group(x):
    result = process(x)
    return [result for item in x]

But I think that it's possible to solve this somehow "smarter". Remember that it's necessary to make calculations only once for each group.
Is it possible to force pd.transform work with array-like result of lambda function like with scalars (just copy it n-times)?
Would be grateful for any advices.
P. S. I understand, that it's possible to use combination of apply and join to solve the original requirement, but the solution with transform has more priority in my case.

A: Sometime transform is a pain to work with If that's not a problem for you I'd suggest you to use groupby + a left pd.merge as in this example:
import pandas as pd
df = pd.DataFrame({"id":[1,1,2,2,2],
                   "col":[1,2,3,4,5]})

# this return a list for every group
grp = df.groupby("id")["col"]\
        .apply(lambda x: list(x))\
        .reset_index(name="out")

#  Then you merge it to the original df
df = pd.merge(df, grp, how="left")

And print(df) returns
   id  col        out
0   1    1     [1, 2]
1   1    2     [1, 2]
2   2    3  [3, 4, 5]
3   2    4  [3, 4, 5]
4   2    5  [3, 4, 5]


text:
Q: How to use js variable in COMPLEX reg expression, not simple one PLEASE STOP MARKING AS DUPLICATE QUESTION BEFORE YOU POST RIGHT ANSWER FOR ME.
This post is not a place where someone is show off his ROUGH search skills on google.
Simple reg exp is not a problem to inject js variable. but what about the complex one like following?
I have a reg expression to check if the URL is from example.com domain.
^(https?:\/\/(.+?\.)?example\.com(\/[A-Za-z0-9\-\._~:\/\?#\[\]@!$&'\(\)\*\+,;\=]*)?)

Now I want to create a function isValidDomainURL(url, domain)
and inside of the function I d like to use above expression replaced example\.com with domain
How can I create a reg expression using js variable inside of it?

A: You can use the RegExp constructor.
var theVariable = "Hello"

var theRegex = new RegExp("." + theVariable + ".");

With your particular URL, it would be something like the following.
var domain = "somedomain.com";
var theRegex = new RegExp("^(https?:\/\/(.+?\\.)?" + domain + "(\/[A-Za-z0-9\\-\\._~:\/\\?#\\[\\]@!$&'\(\)\*\+,;\\=]*)?)")

And then you can use that regex anywhere, or create a new one with a different domain when you want.


text:
Q: How to create a Pandas column to store the number of common elements between two filters of a data frame I have a Pandas data frame with relevant columns A, B, C. For context, there are several C's for every combination of A, B. I would like to compute the number of elements of C that each combination (a_i, b_j) of A, B has in common with the combination (a_0, b_j), where a_0 is fixed.

A
B
C

a_0
b_0
c_0

a_0
b_0
...

a_0
b_0
c_m

a_0
b_1
c_m+1

a_0
...
...

a_0
b_n
c_p

...
...
...

a_q
b_n
c_q

I have tried both using for-loops and pandas.Dataframe.apply, but both were taking too long due to the size of the data frame.


text:
Q: How can i make JavaFX filechooser alwaysonTop of window? How can i make JavaFX filechooser is always on top?
In my application some other dialogs call filechooser and that dialog is set as alwaysonTop, so the filechooser dialog is located behind that dialog.
How can i make the filechooser dialog is alwaysonTop of the window?
I made filechooser like this code.

    public static File getSaveFileFX(final String suffix, String title) {
        File[] selectedFile = {null};
        FileChooser fc = new FileChooser();
        fc.setTitle(title);
        String root = "*" + suffix;
        String fileFormat = suffix + " files";
        fc.getExtensionFilters().addAll(new ExtensionFilter(fileFormat, root));
        fc.setInitialDirectory(new File(getRecentDirectoryPath()));

        PlatformImpl.runAndWait(new Runnable() {
            @Override
            public void run() {
                selectedFile[0] = fc.showSaveDialog(null);
                if(selectedFile[0] != null && !title.equals("Sava To .CSV file")) {
                    //filtering with title
                    mPreferences.put(RECENT_FILE_PATH, selectedFile[0].getAbsolutePath());
                    mPreferences.put(RECENT_DIRECTORY_PATH, selectedFile[0].getParent());
                }
            }
        });

        if(selectedFile[0] != null && !selectedFile[0].getName().endsWith(suffix)) {
            return new File(selectedFile[0].getAbsolutePath()+"."+suffix);
        }else {
            return selectedFile[0];
        }
    }

and the other dialog is set as
dialog.alwaysOnTop(true);

A: You have to set main dialog alwaysOnTop(false);
And the dialog of FileChooser alwaysOnTop(true);
Check this sample, its work.
    public void initializationDialog(Stage stage) {
    stage.resizableProperty().setValue(false);
    stage.setAlwaysOnTop(false);
    stage.toBack();
    openFile();
}

public File openFile(String descriptionOfFile, String extensionOfFile) {
    FileChooser fileChooser = new FileChooser();
    Stage stage2 = new Stage();
    stage2.initOwner(stage);
    stage2.initModality(Modality.WINDOW_MODAL);
    stage2.setAlwaysOnTop(true);
    FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter(descriptionOfFile, extensionOfFile);
    fileChooser.getExtensionFilters().add(filter);
    return fileChooser.showOpenDialog(stage2);
}


text:
Q: Will ASCIITools.StringToAscii do the same job as Encoding.ASCII.GetBytes
Possible Duplicate:
ASCIIEncoding In Windows Phone 7

I am working with Windows Phone 8, and I have noticed that Encoding.ASCII doesn't exist in .NET for Windows Phone, but there is a class called ASCIITools, which contains a method called StringToAscii. which returns a byte array and accepts a string.
I ask because I am trying to convert some code which initially gets a character array from a string like this:
char[] myCharArray = blah.Substring(aaa, bbb).ToCharArray();

And then gets the byte array from the char array by passing it into the GetBytes method:
byte[] blah = Encoding.ASCII.GetBytes(myCharArray, 0, myCharArray.Length);

It looks like this class will allow me to go directly from a string to a byte array like so:
byte[] blah = ASCIITools.StringToAscii(blah.Substring(aaa, bbb));

Will this work?


text:
Q: Why is it not showing data from controller in jsp file? HomeController.java
package myapp;

import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@EnableWebMvc
@Configuration
@Controller
public class HomeController {
    @GetMapping(value = "/")
    public ModelAndView index(ModelMap model) {
        ModelAndView mav = new ModelAndView("index");
        mav.addObject("greeting", "Welcomes you to Spring!");
        model.addAttribute("message", "Hello world");
        return mav;
        //return "index";
    }
}

index.jsp file
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Insert title here</title>

<%
    String name = (String) request.getAttribute("message");
%>

<%= name %>

    ${message}
    ${greeting }
    <%@include file='body.html'%>

In index.jsp file, it is not showing the data for ${message} and ${greeting}. How can I solve this? I am using Tomcat 9.


text:
Q: Disable ForwardX11Timeout without ForwardX11Trusted in OpenSSH Client? By default, recent versions of OpenSSH automatically set ForwardX11Timeout to 20 minutes if you set ForwardX11Trusted to no.
This means that 20 minutes after you start your ssh connection, you can't open any more X clients, because the authentication token has expired. Especially bad if you try to use this with long-lived connections and ControlMaster.
I've tried disabling by setting to 0 (does not work, causes instant expiration) and by setting to a really long value (do not do this, it will crash your X server. Limit is somewhere between 3 and 4 weeks).
How can I completely disable the timeout?

A: At the present time it seems you can't reliably disable the time out completely. Nevertheless the patch needed shouldn't be too much intrusive so if you are able to update/recompile your ssh there should be a way out of it. You might want to watch this question on the upstream mailing list for possible replies.

A: There was a patch 2018-04 and discussion 2018-06 but my search of mailing list archive by subject lines alone suggests it was not yet accepted as of 2019-04.
Duplicating some related info I posted at https://superuser.com/a/1429080/1027014 just now -

The maximum timeout is uint_max of milliseconds minus some slack, just over 24 days.  OpenSSH_7.4p1 will accept ssh -o ForwardX11Timeout=2147423s -X ... which is the best answer I can make now.  ForwardX11Timeout above this may crash the XServer in some version combinations.
On MacOS with XQuartz, I have seen Warning: untrusted X11 forwarding setup failed: xauth key data not generated and upon digging further, /opt/X11/bin/xauth:  timeout in locking authority file /var/folders/..../xauthfile .


text:
Q: Width and Height 100percent is not working Lets say i have two divs

Div 1 have this style
width: calc(100% - 22rem);
min-height: calc(100% - 7.75rem);

How can i set div 2 to same size as div1?
Because width:100% and height:100% wont work

A: position: absolute;

works fine as mentioned by Barbu Barbu
Here's a fiddle for visualization
https://jsfiddle.net/rvzqsgc1/3/

body {
  background-color: black;
}

.div1 {
  position: absolute;
  width: calc(100% - 22rem);
  min-height: calc(100% - 7.75rem);
  background-color: white;
}

.div2 {
  width: 100%;
  background-color: green;
  height: 100%;
  position: absolute;
}

A: Try like this, It will work for you.

  body {
      background: black
    }

    .one {
      position: absolute;
      background-color: #FFF;
      width: calc(100% - 22rem);
      min-height: calc(100% - 7.75rem);
    }
    .two {
      position: absolute;
      width: 100%;
      background-color: orange;
      height: 100%;
    }


text:
Q: neo4j-shell readonly model can't work with index I modified the demo EmbeddedNeo4jWithIndexing.java(create node with index).
I Comment all shutdown() method,
after do it, I open the database by neo4j-shell -readonly,then I run
start n=node:nodes("*:*") return n;

I get 0 rows
if I open the database without -readonly ,and run the command above,it successed!
I am very confused about it
I tried 1.8.2 and 1.9

A: We disallow read-only access to running databases because of lucene ignoring the R/O aspect and still doing merges asynchronically behind the scenes, clashing with the merge threads of the live database.


text:
Q: Changing siteurl breaks site I am hosting my site on amazon ec2. I have purchased a domain name via godaddy and have forwarded it to the IP address of my amazon instance. I forwarded with masking turned on so that users do not see the IP in the address bar. It works fine, when I go to mysite.com the content loads.
I now need to change the wordpress address and the site address to mysite.com since they are defaulting to the ip address and i want to use permalinks for the rest of the site. When I do this the site no longer works. Site won't load and I can't access admin.
If I change just the wordpress address to mysite.com and leave the site address as the IP I am given an admin login page with broken css but when I try to use it nothing happens.
I have attempted to change the urls via the admin interface, directly in the database (updating siteurl & home in the wp_options table) and via the wp-config.php. all methods produce the same result.
I see lots of questions posted that are similar to this but seem to find solutions that don't work for me.
Any ideas on what I might be missing here?? I'm kind of running out of ideas.

A: Put this in your theme template functions.php
update_option( 'siteurl', 'http://example.com' );
update_option( 'home', 'http://example.com' );


text:
Q: Protocol function implementation without actually conforming to a protocol I am a beginner Swift learner and I have a question about protocols. I have followed a tutorial that teaches you about linked lists, which is as follows:
Node:
class LinkedListNode<Key> {
    let key: Key
    var next: LinkedListNode?
    weak var previous: LinkedListNode?

    init (key: Key) {
        self.key = key
    }
}

And the linked list:
class LinkedList<Element>: CustomStringConvertible {
    typealias Node = LinkedListNode<Element>

    private var head: Node?

    // irrelevant code removed here

    var description: String {
        var output = "["
        var node = head
        while node != nil {
            output += "\(node!.key)"
            node = node!.next
            if node != nil { output += ", " }
        }
        return output + "]"
    }
}

The var description: String implementation simply lets you to print each elements in the linked list.
So far, I understand the structure of the linked list, my problem isn't about the linked list actually. What I don't understand is the protocol CustomStringConvertible. Why would it be wrong if I have only the var description: String implementation without conforming to the protocol? I mean, this protocol just simply say "Hey, you need to implement var description: String because you are conformed to me, but why can't we just implement var description: String without conforming to the protocol?
Is it because in the background, there is a function or some sort that takes in a type CustomStringConvertible and run it through some code and voila! text appears.

A: Why can't we just implement var description: String without conforming to the protocol?
Compare:
class Foo {
    var description: String { return "my awesome description" }
}

let foo = Foo()

print("\(foo)") // return "stackoverflow.Foo" (myBundleName.Foo)

and
class Foo: CustomStringConvertible {
    var description: String { return "my awesome description" }
}

let foo = Foo()

print("\(foo)") // return "my awesome description"

When you use CustomStringConvertible, you warrant that this class have the variable description, then, you can call it, without knowing the others details of implementation.
Another example:
(someObject as? CustomStringConvertible).description

I don't know the type of someObject, but, if it subscriber the CustomStringConvertible, then, I can call description.

A: You must conform to CustomStringConvertible if you want string interpolation to use your description property.
You use string interpolation in Swift like this:
"Here's my linked list: \(linkedList)"

The compiler basically turns that into this:
String(stringInterpolation:
    String(stringInterpolationSegment: "Here's my linked list: "),
    String(stringInterpolationSegment: linkedList),
    String(stringInterpolationSegment: ""))

There's a generic version of String(stringInterpolationSegment:) defined like this:
public init<T>(stringInterpolationSegment expr: T) {
  self = String(describing: expr)
}

String(describing: ) is defined like this:
public init<Subject>(describing instance: Subject) {
  self.init()
  _print_unlocked(instance, &self)
}

_print_unlocked is defined like this:
internal func _print_unlocked<T, TargetStream : TextOutputStream>(
  _ value: T, _ target: inout TargetStream
) {
  // Optional has no representation suitable for display; therefore,
  // values of optional type should be printed as a debug
  // string. Check for Optional first, before checking protocol
  // conformance below, because an Optional value is convertible to a
  // protocol if its wrapped type conforms to that protocol.
  if _isOptional(type(of: value)) {
    let debugPrintable = value as! CustomDebugStringConvertible
    debugPrintable.debugDescription.write(to: &target)
    return
  }
  if case let streamableObject as TextOutputStreamable = value {
    streamableObject.write(to: &target)
    return
  }

  if case let printableObject as CustomStringConvertible = value {
    printableObject.description.write(to: &target)
    return
  }

  if case let debugPrintableObject as CustomDebugStringConvertible = value {
    debugPrintableObject.debugDescription.write(to: &target)
    return
  }

  let mirror = Mirror(reflecting: value)
  _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: false)
}

Notice that _print_unlocked only calls the object's description method if the object conforms to CustomStringConvertible.
If your object doesn't conform to CustomStringConvertible or one of the other protocols used in _print_unlocked, then _print_unlocked creates a Mirror for your object, which ends up just printing the object's type (e.g. MyProject.LinkedList) and nothing else.

A: CustomStringConvertible allows you to do a print(linkedListInstance) that will print to the console whatever is returned by the description setter.
You can find more information about this protocol here: https://developer.apple.com/reference/swift/customstringconvertible


text:
Q: Not understanding F# syntax with type conversion This works:
let a = 3
let b = string b
let c = a |> string

but:
let a = string j.SelectToken("hello")

doesn't work, while
let a = j.SelectToken("hello") |> string

works.
why is that?

A: The compiler thinks you want to pass j.SelectToken to string. Remember, functions are values, so that is legal. Any of these work:
let a = j.SelectToken "hello" |> string
let a = string (j.SelectToken "hello")
let a = string <| j.SelectToken "hello"
let a = "hello" |> j.SelectToken |> string

A: Unless you wrap j.SelectToken("hello") in parentheses, you get this error:
Successive arguments should be separated by spaces or tupled,
and arguments involving function or method applications should be parenthesized
F# Compiler(597)

Why has already been answered at https://stackoverflow.com/a/23848236/5652483
There is an open issue with interesting discussion at https://github.com/fsharp/fslang-suggestions/issues/644


text:
Q: AppCompat v7 and DatePicker render issue Recently I have read a chapter about dialogs in The Big Nerd Ranch Guide (2nd edition) and I have done everything by the book. However there are some issues, which are not mensioned in the book. Preview area of Intellij Idea doesn't work correctly with AppCompat themes.
This is my current theme:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
     <!-- Customize your theme here. -->
</style>

And this is what I have in preview area:

In the Internet I have read that using Base.Theme.AppCompat.Light.DarkActionBar may help. It removes the message, but ActionBar dissapeares also.
Oh, and DatePicker doesn't work with both and any Material Design:

This is just a render issue, because both themes work fine on devices. Can someone try to preview DatePicker in IDEA and Android Studio with AppCompat theme? May be this is just an IDEA issue.
P.S. dialog_date.xml
<?xml version="1.0" encoding="utf-8"?>
<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/dialog_date_date_picker"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:calendarViewShown="false"
/>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.criminalintent" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
                android:name=".CrimeListActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".CrimePagerActivity"
            android:label="@string/app_name" >
        </activity>
    </application>

</manifest>

Whole project: https://onedrive.live.com/redir?resid=4653F2D263EA4131!21585&authkey=!AESze90_ZZ0p9WY&ithint=folder%2cproperties

A: Make your style.xml look like this, toolbar will show up:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
     <!-- Customize your theme here. -->
</style>
<style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
</style>

And your DatePicker needs to loo like this:
<DatePicker
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:datePickerMode="spinner"
    android:id="@+id/datePicker" />

If you need CalendarView in your xml add this insted of DatePicker:
<CalendarView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/calendarView1" />

A: Switching Themes
If you look at the declaration for Theme.AppCompat.Light.DarkActionBar, it aliases directly to Base.Theme.AppCompat.Light.DarkActionBar in AppCompat's values/themes.xml file:
<!-- Platform-independent theme providing an action bar in a dark-themed activity. -->
<style name="Theme.AppCompat.Light.DarkActionBar" parent="Base.Theme.AppCompat.Light.DarkActionBar" />

source
This isn't aliased in any of the other device configurations (e.g. values-v23/themes.xml, values-v18/themes.xml, etc). Have a look at the resouces for AppCompat here. This means that for every device, Theme.AppCompat.Light.DarkActionBar will always and only alias to Base.Theme.AppCompat.Light.DarkActionBar.
The docs for the Base theme make this even more clear:

Themes in the "Base.Theme" family vary based on the current
  platform version to provide the correct basis on each device. You
  probably don't want to use them directly in your apps.
Themes in the "Theme.AppCompat" family are meant to be extended or
  used directly by apps.

source
So your switching from Theme.AppCompat.Light.DarkActionBar to Base.Theme.Light.DarkActionBar will never affect how things are displayed on actual devices and really isn't a change. The fact that Android Studio behaved differently is a problem with Android Studio (which I was unable to reproduce using your code on AS 2.0 preview 9).
 Problem with Android Studio
I'll say that the Design tab has always been a bit flaky. It's getting better but hasn't always played nice, especially with support library stuff. To change your app's theme (even if what I said above wasn't true) just to make the Design tab look pretty is probably a bad idea. Think about your users. If you really want to know what your screen looks like, then deploy it to a real device or emulator.
Dialogs
I was also unable to reproduce your Dialog problem in AS 1.4 (stable) or AS 2.0 preview 9 (canary, ATM). But since your entire layout file is a DatePicker, I don't think you will get much benefit. This is even less beneficial when you consider that your DatePicker will be displayed in a dialog (which the Design tab is unable to simulate). I don't mean to sound harsh but you might just have to bite the bullet and use an emulator or physical device.

A: Shitty Android Studio 1.5.0 should be updated to 1.5.1. So easy


text:
Q: WCF service problem with SSL I have problem with call WCf service over SSL from console app. WCF service is on Windows Server 2003. It's simple math service. The WCF service and client are on the same computer. It's test, I call service on localhost.
web.confing
<?xml version="1.0"?>
<configuration>
    <system.serviceModel>
        <services>
            <service name="Service.CalculatorService" behaviorConfiguration="CalculatorServiceBehavior">
                <endpoint address="https://machineName/https/calculatorservice.svc" name="myEndpoint" binding="basicHttpBinding"
                  bindingConfiguration="Binding1" contract="Service.ICalculator"/>
            </service>
        </services>
        <bindings>
            <basicHttpBinding>
                <binding name="Binding1">
                    <security mode="Transport">
                        <transport clientCredentialType="None"/>
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <behaviors>
   <serviceBehaviors>
    <behavior name="CalculatorServiceBehavior">
      <serviceMetadata httpsGetEnabled="true"
        httpsGetUrl="https://machineName/https/calculatorservice.svc" />
     <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
   </serviceBehaviors>
  </behaviors>
    </system.serviceModel>
    <system.web>
        <compilation debug="true"/></system.web></configuration>

If I call service from Visual Studio examaple :  http://localhost:2039/CalculatorService.svc
I get error :
The protocol 'https' is not supported. I think it s ok.
But if I call service from browser I get error :
A registration already exists for URI 'https://machineName/https/CalculatorService.svc'.
What is bad? Can anybody help me, thank you.

A: Remove the "address" attribute from the endpoint element- when you're hosting in IIS, it automatically supplies this.

A: Visual Studio Development Server does not support https. You need to host your service in IIS
http://msdn.microsoft.com/en-us/library/vstudio/aa751792(v=vs.100).aspx


text:
Q: How do I show the pointer after touch interaction in Windows 8 When you touch the screen in Windows 8, the mouse pointer  is hidden until you move the mouse (or other pointing device).  This happens in both desktop and Metro interfaces.
We have a program that allows people to move the mouse pointer using other input methods (such as a joystick), so I need to ensure the mouse pointer is visible.
How can I force the mouse pointer to be displayed?

A: you can set the flag of touch feedback.
[setting] ->[control panel]->[pen and touch]->[touch feekback] item,there is a checkbox that is [show visual feedback when touch the screen].If you cann't select the checkbox, you can show the mouse pointer without coding anything when touching the screen.

A: You can inject mouse movement before you start joystick control, using Windows API:
POINT p;
GetCursorPos(&p);

MOUSEINPUT mi;
mi.dx = (LONG) ((p.x * 65535) / screen_width);
mi.dy = (LONG) ((p.y * 65535) / screen_height);
mi.mouseData = 0;
mi.dwFlags = type | MOUSEEVENTF_ABSOLUTE;
mi.time = 0;
mi.dwExtraInfo = NULL;

INPUT input;
input.type = INPUT_MOUSE;
input.mi   = mi;

SendInput(1, &input, sizeof(INPUT));


text:
Q: download multiple files from browser How do I download multiple files at once from a browser without combining them into single file? I found all kinds of multiple file uploaders, but downloaders are missing. There is only JUpload, but it's old and became buggy recently. I believe both Java and Flash can do this: select a folder at client's HD and download everything there.

A: The only solution I can think about is a performing multiple AJAX calls to each file separately. All this calls may be invoked by single click of user. This will look OK in Chrome because it does not ask (by default) where to put the downloaded file and put all files into pre-configured download directory.
I think that in Firefox the user will see pop-up that asks what to do with file (download or open) for each file separately.
MSIE will ask where to save each file.
Bottom line: this solution will look good in Chrome only. Other browsers should be configured properly.


text:
Q: how to apply a mask to an item coming from an API with Javascript I have a basic CRUD situation, where in the form, when I send the data, it inserts the mask normally, and when sending it to my local API, I format it and leave it in numeric format. But how am I going to apply the mask again on the item being displayed in a grid?
in my form, is like this

and on the grid, it displays like this

now, I need to apply the mask again, but on the grid that is showing. How to make?
to show the items on the grid, I am doing this via Javascript:
const exibirEmpresas = (u) => {
  Array.from(u).forEach((lista) => {
    dadosEmpresa += `

        ${lista.idEmpresa}
        ${lista.nomeEmpresa}
        ${lista.email}
        ${lista.cnpj}
        ${lista.dataCadastro}
        ${lista.dataAtualizacao}

          <button id="atualiza-empresa" onclick="editItem(${lista.idEmpresa})">Editar</button>

          <button class="deletebtn" onclick="removeItem(${lista.idEmpresa})">Excluir</button>

        `;
  });
  listaEmpresa.innerHTML = dadosEmpresa;
};

// GET

fetch(urlAPI)
  .then((s) => s.json())
  .then((dados) => exibirEmpresas(dados));

A: I understand that you are essentially looking for a way to turn a 14-digit string like "19879847984784" to "19.879.847/9847-84".
You can add this JavaScript code to your script. The HTML is just an example with hard coded values.

function formatCnpj() {
    for (let td of document.querySelectorAll(".cnpjCad")) {
        td.textContent = td.textContent
               .replace(/\D/g, "")
               .replace(/(..)(...)(...)(....)/, "$1.$2.$3/$4-");
    }
}

formatCnpj();
table { border-collapse: collapse }
td, th { border: 1px solid }

    28
    John Larkin
    john.larkin@x.com
    19961423596110
    2000-09-09
    2020-09-09

      <button id="atualiza-empresa" onclick="editItem(${lista.idEmpresa})">Editar</button>

      <button class="deletebtn" onclick="removeItem(${lista.idEmpresa})">Excluir</button>

    12
    Helene Park
    helene.park@n.com
    19879847984784
    2000-01-01
    2020-01-01

      <button id="atualiza-empresa" onclick="editItem(${lista.idEmpresa})">Editar</button>

      <button class="deletebtn" onclick="removeItem(${lista.idEmpresa})">Excluir</button>


text:
Q: PHP: Edit entry in array depending on value from another array I'm trying to figure out how I can change a value in a array if the corresponding value in another array is 0.
For all Speed[x] = 0 the corresponding Direction[x] is also = 0.
Given the two arrays below:
Speed
(
    [0] => 2.2
    [1] => 1.3
    [2] => 0
    [3] => 0
    [4] => 0
    [5] => 1.1
)

Direction
(
    [0] => 126.2
    [1] => 159.8
    [2] => 0
    [3] => 0
    [4] => 0
    [5] => 163.8
)

I need to loop through the Direction array and change all values that has a corresponding 0 entry in the Speed array to the previous entry in the Direction array that is bigger than 0 .
So if Speed [2], Speed [3], Speed [4] = 0 then Direction[2], Direction [3], Direction [4] should be = Direction [1] in the example below since Direction[1] is the first previous entry bigger than 0.
That would give me:
Speed
(
    [0] => 2.2
    [1] => 1.3
    [2] => 0
    [3] => 0
    [4] => 0
    [5] => 1.1
)

Direction
(
    [0] => 126.2
    [1] => 159.8
    [2] => 159.8
    [3] => 159.8
    [4] => 159.8
    [5] => 163.8
)

Can anyone point me in the right direction on how I could get this done?

A: Try Replacing Direction Array Value with after/before element when you find speed array value to 0
<?php
    $Speed = array("2.2","1.3","0","1.8","1.2");
    $Direction = array("159.2","159.8","0","161.4","1.2");
    for($i=0;$i<count($Speed);$i++)
    {
        if($Speed[$i] == '0')
        {
            $Direction[$i] = $Direction[1];
        }
    }
    print_r($arr2);
    ?>

o/p
Array ( [0] => 159.2 [1] => 159.8 [2] => 159.8 [3] => 161.4 [4] => 1.2 )

A: for($i=0;$i<count($speed);$i++){
 if($speed[$i] == 0){
   $direction[$i] = $direction[$i-1];
   }
 }


text:
Q: Android with mySQL connection, Eclipse? I simply have a small question..
I was wondering about Android connection with MySql , As I know there is no any direct connection between Android with MySql, we need to use JSON or any other library to connect. Well using JSON and configure it with some PHP files, is this the only way we can get and query datas from mysql,so far, and is it desirable this way??? or there are some other way how to get the datas  from mysql into listview or wherever in Android?
Thanks,

A: You can deploy the mysql JDBC driver into your Android application.  There are several blogs that show you how to do it. How functional it will be I can't tell. Just keep in mind that if you want Android devices to connect to your mysql server directly you need to expose the mysql server to the internet directly. This is generally not recommended. Also the data flowing between mysql and the device will be unencrypted.
Essentially doing this moves your architecture back to client server model. If you later wanted to support iPhones, blackberry or Windows mobile you will have to make those devices also connect directly to mysql. By using a webservice or even your own custom developed server you can remove the dependency on the MySQL driver. In the long run this will probably be a better model to follow.
The choice is yours however.


text:
Q: DynamoDB query subsegments show some of them take way too long - How to debug I tried using https://github.com/shelfio/dynamodb-query-optimized to speed up the dynamodb response time when querying time-series data. Nothing fancy, uses a GSI for the query (id and timestamp) and uses them in the key expression. Not much to filter out in the filter expression so the index is optimized.
For some reason, if I use the queryOptimized method (that queries 2-way i.e scan forward and backward), some of the dynamodb query subsegments start taking way too long. In the range of 16seconds-25seconds which is killing the performance and resulting in API gateway timeouts.
The first 20-25 subsegments seem to start at approximately the same time and have decent performance i.e under 500ms, However, after 20-25 subsegments, It starts about 300ms later and the duration of most of these subsegments is really long.
How do I debug what is going on here? Doesn't seem to give any further info in traces. Retries are 0 for all of those subsegments, No failures or errors either. The table is configured to have on-demand capacity so do not imagine capacity to be the issue. Lambda function also has the max (10GB memory allocated) to it. Any ideas on how to figure out what's going on?


text:
Q: Django (audio) html error I have this project with django, everything working fine.
But when I go to a page where songs will be showen, and also the user have the option to play the songs, I get an error even if everything is working fine.
In the html page, when I remove the audio option " <'audio'>...<'/audio'>
I get no errors, but once I get it back, the error back with it, so the problem is with the <'audio'> tag I guess
The view :
@login_required()
def songs(request, filter_by=None):

    song_ids = []
    for album in Album.objects.filter(user=request.user):
        for song in album.song_set.all():
            song_ids.append(song.pk)
    users_songs = Song.objects.filter(pk__in=song_ids)

    if filter_by == 'favorites':
        users_songs = users_songs.filter(is_favorite=True)

    return render(request, 'music/songs.html', {
        'song_list': users_songs,
        'filter_by': filter_by,
    })

the bit of code of html page:

  <audio controls controlsList="nodownload">
         Your browser does not support the audio element.
   <source src="{{ song.audio_file.url }}" type="audio/wav">
 </audio>

and this is the error :

Traceback (most recent call last):   File
 "C:\Users\elmou\AppData\Local\Programs\Python\Python36-    32\lib\wsgiref\handlers.py",
 line 141, in run
      self.handle_error()   File   "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-   packages\django\core\servers\basehttp.py",
  line 88, in handle_error
     super(ServerHandler, self).handle_error()   File   "C:\Users\elmou\AppData\Local\Programs\Python\Python36-  32\lib\wsgiref\handlers.py",
  line 368, in handle_error
    self.finish_response()   File   "C:\Users\elmou\AppData\Local\Programs\Python\Python36-  32\lib\wsgiref\handlers.py",
  line 180, in finish_response
      self.write(data)   File     "C:\Users\elmou\AppData\Local\Programs\Python\Python36-   32\lib\wsgiref\handlers.py",
  line 274, in write
     self.send_headers()   File   "C:\Users\elmou\AppData\Local\Programs\Python\Python36-  32\lib\wsgiref\handlers.py",
 line 331, in send_headers
    if not self.origin_server or self.client_is_modern():   File   "C:\Users\elmou\AppData\Local\Programs\Python\Python36-  32\lib\wsgiref\handlers.py",
  line 344, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is not subscriptable

 During handling of the above exception, another exception occurred:

  Traceback (most recent call last):   File
  "C:\Users\elmou\AppData\Local\Programs\Python\Python36-  32\lib\socketserver.py",
  line 639, in process_request_thread
 self.finish_request(request, client_address)   File      "C:\Users\elmou\AppData\Local\Programs\Python\Python36-  32\lib\socketserver.py",
  line 361, in finish_request
      self.RequestHandlerClass(request, client_address, self)   File    "C:\Users\elmou\AppData\Local\Programs\Python\Python36-   32\lib\socketserver.py",
line 696, in __init__
    self.handle()   File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\servers\basehttp.py",
line 155, in handle
handler.run(self.server.get_app())   File   "C:\Users\elmou\AppData\Local\Programs\Python\Python36-   32\lib\wsgiref\handlers.py",
 line 144, in run
     self.close()   File   "C:\Users\elmou\AppData\Local\Programs\Python\Python36-  32\lib\wsgiref\simple_server.py",
 line 35, in close
     self.status.split(' ',1)[0], self.bytes_sent AttributeError: '     NoneType' object has no attribute 'split'

the error is so long, but it s the same over and over again


text:
Q: Can't get Swagger Annotations output on Websphere Liberty Profile I'm trying to use Swagger (1.5.12) Annotations in my web application deployed to WAS Liberty Profile 16.0.0.3.
However, when I access the /swagger.json URL, the following exception is thrown:

[err] [Default Executor-thread-13] WARN org.reflections.Reflections - could not create Vfs.Dir from url. ignoring the exception and continuing
  [err] org.reflections.ReflectionsException: could not create Vfs.Dir from url, no matching UrlType was found [wsjar:file:/opt/ibm/WebSphere/Liberty-ND-16.0.0.3/wlp/usr/servers/defaultServer/workarea/org.eclipse.osgi/61/data/cache/com.ibm.ws.app.manager_87/.cache/!/WEB-INF/classes/]
  either use fromURL(final URL url, final List urlTypes) or use the static setDefaultURLTypes(final List urlTypes) or addDefaultURLTypes(UrlType urlType) with your specialized UrlType.
  [err]     at org.reflections.vfs.Vfs.fromURL(Vfs.java:109)

Do you know how to overcome this issue?
I'd like to use this swagger.json output with the REST API Documentation that comes with WLP under /ibm/api/explorer/ context.
Thanks, any suggestions are really welcome!

A: I solved the problem adding the following setting in server.xml:
<classloading useJarUrls="true"/>

I also had to downgrade to Swagger 1.5.3

A: Yes, at the moment WebSphere Liberty supports Swagger annotations 1.5.3.  You won't get a compiler error if using 1.5.4, but full support for that version is not there yet.
The version of the annotations package in Open Source moves up quickly, but rest assured that in the next few months WebSphere Liberty will synchronize with the latest versions.


text:
Q: Passing a string to a handler function in Go I have a generic Webserver which I want to use on different domains / servers.
For setting up each server I simply read a JSON config file with all necessary information. One would be for example the redirect for all traffic which reaches port 80 and forward it to a TLS service. Since I don't want to make the config object global. How can I pass the content from my inputFromConfigFile to the redirectTLS function?
Here is an example:
func main(){
  var inputFromConfigFile = "https://www.example.com:443"

  go func() {
    if err := http.ListenAndServe(":80", http.HandlerFunc(redirectTLS)); err != nil {
      log.Fatalf("ListenAndServe error: %v", err)
    }
  }()
}

//Pass the above string to this function:

func redirectTLS(w http.ResponseWriter, r *http.Request) {
  http.Redirect(w, r, "https://www.example.com:443"+r.RequestURI,http.StatusMovedPermanently)
}

A: You can define a custom Handler (could be implemented as a struct) as long as it matches the http.Handler interface. The config could be saved inside the Handler as a struct field.
type Handler struct {
  // config goes here
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  // anything that handler needs to do here
}

Example: https://pkg.go.dev/net/http#example-Handle

A: You can define redirectTLS as an inline closure function directly in main:
var inputFromConfigFile = "https://www.example.com:443"

go func() {
    err := http.ListenAndServe(":80", func(w http.ResponseWriter, r *http.Request) {
        http.Redirect(w, r, inputFromConfigFile+r.RequestURI, http.StatusMovedPermanently)
    })

    if err != nil {
        log.Fatalf("ListenAndServe error: %v", err)
    }
}()

A: I would make the config object global.
Otherwise, you can define a function that accepts the config as an argument, and returns a handler function that closes over the configuration object:

var inputFromConfigFile = "https://www.example.com:443"

http.ListenAndServe(":80", createHandler(inputFromConfigFile))

// ...

func createHandler(config string) http.HandlerFunc {
  return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, config+r.RequestURI,http.StatusMovedPermanently)
  })
}


text:
Q: Grails Database Connection Problem When Deployed I can successfully run my Grails application in Jetty.  It succeeds in connecting to my MsSql database and everything is fine.  When I deploy that same application in Tomcat 6 on the same machine, I receive the following error on startup in the Tomcat log:
Caused by: java.net.ConnectException: Connection refused: connect

I don't believe that my MsSql server is the issue since I have another Java application running in the same instance of Tomcat and accessing the same database server successfully.
The connection string is exactly the same when I deploy it in Jetty and in Tomcat.  Any ideas why I can't connect to my database when I deploy my Grails app in Tomcat 6?  I can't seem to access any databases when my Grails app deployed in Tomcat.  (My other Java app (Confluence) has no problem connecting.
Here is my connection info:
dataSource {
    pooled = true
    driverClassName = "net.sourceforge.jtds.jdbc.Driver"
    username = "user"
    password = "pass"
}
hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=true
    cache.provider_class='com.opensymphony.oscache.hibernate.OSCacheProvider'
}
// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "update" // one of 'create', 'create-drop','update'
            url = "jdbc:jtds:sqlserver://localhost:1143/holidayCards"
        }
    }
    test { //for AD-DEV02
        dataSource {
            dbCreate = "update"
            url = "jdbc:jtds:sqlserver://AD-DEV02:1237/holidayCards;instance=SQL2005"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:jtds:sqlserver://SQL:1433/holidayCards"
        }
    }
}

I always deploy as 'test':
grails test war

As you'll see from my answer below, I don't think this is a connection issue since I was able to get to work successfully when I downgraded from grails 1.1beta1 to 1.0.4.
Any help is appreciated,
Andrew

A: What does your DataSource.groovy file look like? When you run your app with 'grails run-app', Grails uses the datasource in the "development" section. When you produce a war file with 'grails war' and deploy it to an application server, Grails uses the datasource in the "production" section. You may need to make sure that your development and production datasource are configure the same.

A: This is an issue with grails 1.1beta1.  When I reverted my application to grails 1.0.4, it seemed to work.  Unfortunately, I had to change a couple pieces of code because the beta version of grails fixed some bugs, but this seems to be rooted in the version of grails I was using.
I just created an empty grails application using 1.1beta1 and I was able to successfully deploy it in Tomcat (and access the database).  This makes me think that there are some other settings in my project that don't play well with the beta version.  Perhaps it's my jquery plugin.  Perhaps it was upgrading my project from grails 1.0.4 to 1.1beta1
This doesn't quite solve the issue, but it narrows it.
Andrew


text:
Q: TSQL procedure call to PLSQL procedure : ORA-06502: PL/SQL: numeric or value error I have a T-SQL procedure calling an Oracle procedure passing in some parameters.
My oracle procedure works fine and returns the output parameters as expected.
However when calling the oracle procedure from the T-SQL procedure, I have the following error. I can't understand why am I getting this. Varchars are being used in both procedures.

(1 row(s) affected) OLE DB provider "OraOLEDB.Oracle" for linked
  server "ORA_LINK_SERVER" returned message "ORA-06502: PL/SQL: numeric
  or value error ORA-06512: at "DBNAME.GETSHELLACNOANDINSTRUCTIONNO",
  line 7".
(1 row(s) affected)
(1 row(s) affected) Msg 7215, Level 17, State 1, Procedure
  USP_TXN_PF_CLIENT_URL_NEW, Line 56 Could not execute statement on
  remote server 'ORA_LINK_SERVER'.

This is my T-SQL procedure
    USE [TVE]
    GO
    /****** Object:  StoredProcedure [CompanyName].[USP_TXN_PF_CLIENT_URL]    Script Date: 12/29/2016 11:14:02 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

        --To test +
        /*
            Declare @ReturnString varchar(255)
            EXEC [CompanyName].[USP_TXN_PF_CLIENT_URL_NEW] 'CompanyName','50585609',@ReturnString = @ReturnString OUTPUT
            select @ReturnString
    */

   /*
        ALTER TABLE [dbo].[PF_CLIENT_URLS]
        ADD [STATUS] VARCHAR(1) NULL
        GO

        SELECT * FROM [dbo].[PF_CLIENT_URLS]
    */
        ALTER PROCEDURE [CompanyName].[USP_TXN_PF_CLIENT_URL_NEW]
        (
            @IN_PMancoID        VARCHAR(10),
            @IN_PInvestorRef    VARCHAR(12),
            @ReturnString       varchar(255) OUTPUT
        )
        AS
        BEGIN
        DECLARE @runStr VARCHAR(2000)
        DECLARE @URL varchar(36)
        DECLARE @MessageID AS VARCHAR(40), @RecipientID AS VARCHAR(40), @FileName VARCHAR(40),@ResponseFileName VARCHAR(40), @Message VARCHAR(500),
                @Cell VARCHAR(35), @OUT_ShellAccountNumber VARCHAR(40), @OUT_InstructionNumber VARCHAR(40)

        DECLARE @ParamKeys VARCHAR(max), @ParamValues VARCHAR(max), @Return_ID INT, @Current_User_ID INT,
                @ErrorNumber INT, @ErrorSeverity INT, @ErrorState INT, @ErrorLine INT,
                @ErrorMessage nVARCHAR(2048), @LogInfo_ID INT, @ProcedureName NVARCHAR(126),
                @ProfileName VARCHAR(50), @Recipients VARCHAR(max), @Subject VARCHAR(100), @Body VARCHAR(max)

        Set @ProcedureName = 'YYYY.USP_PF_CLIENT_URL_NEW'
        Set @ParamKeys = ''
        Set @ParamValues = ''
        set @URL = newID()

        Set @ParamKeys =    'IN_PMancoID' + '|' +
                            'IN_PInvestorRef'

        Set @ParamValues =  ISNULL(CONVERT(VARCHAR(max),@IN_PMancoID),'NULL') + '|' +
                            ISNULL(CONVERT(VARCHAR(max),@IN_PInvestorRef),'NULL')

        exec [DYNAMIC].[ss_StoredProcLogInfo_Save]  @ProcName = @ProcedureName,
                                                    @ParameterKeys = @ParamKeys,
                                                    @ParameterValues = @ParamValues,
                                                    @User_ID = @Current_User_ID,
                                                    @Return_ID = @Return_ID OUTPUT

        exec ('CALL DBNAME.GETSHELLACNOANDINSTRUCTIONNO(?,?,?)', @IN_PInvestorRef, @OUT_ShellAccountNumber, @OUT_InstructionNumber) AT ORA_LINK_SERVER

        INSERT INTO [dbo].[TableName]([UserID],[MancoID],[Reference],[DateCreated],[LoginAttempts],[STATUS],[ShellAccount],[InstructionNumber])
        values(ISNULL(@URL, ''),'CompanyName',ISNULL(@IN_PInvestorRef, ''),getdate(),0,'I', ISNULL(@OUT_ShellAccountNumber,''),ISNULL(@OUT_InstructionNumber,''))

        set @ReturnString = @URL
        --Select @ReturnString as ReturnString
        END

And this is my oracle procedure. The link server is fine.
CREATE OR REPLACE
PROCEDURE GETSHELLACNOANDINSTRUCTIONNO
( IN_PInvestorRef IN VARCHAR2(12)
, OUT_ShellAccountNumber OUT VARCHAR2(40)
, OUT_InstructionNumber OUT VARCHAR2(40)
) AS
BEGIN
  Select SHELL_ACCOUNT, INSTRUCTIONNUMBER into OUT_ShellAccountNumber, OUT_InstructionNumber
  from pf
  where client_id = IN_PInvestorRef;
  EXCEPTION WHEN OTHERS THEN
  dbms_output.put_line(SQLERRM);
END GETSHELLACNOANDINSTRUCTIONNO;


text:
Q: Possible to pause console operation? I have many working jobs running on different consoles.
They almost occupied all the CPU usage, which caused me hard to control the system ( very slow response time )
Is there any way to pause these consoles? or any other ways?
#update
I am actually building Yocto in many different consoles, it seems hard to adjust a specific process, and when building Yocto, there are many different processes running, and they may end and start another new one repeatedly.

A: If it is a foreground process, you can use ctrl +z to pause the execution of foreground commands and put the process into the background, where it can be reawakened with fg and put into the foreground
liruilong@liruilongs:~$ jobs
liruilong@liruilongs:~$ sleep 2000
^Z
[1]+ Stopped sleep 2000
liruilong@liruilongs:~$ jobs
[1]+ Stopped sleep 2000
liruilong@liruilongs:~$ fg
sleep 2000

In addition to modifying the process priority,Consider using cgroup to limit resources when the process starts
If you use systemd, you can limit the resources of the process via cgroup.
┌──[root@liruilongs.github.io]-[~]
└─$ systemd-run -p MemoryLimit=5M -p CPUShares=100 --unit=sleep-50 --slice=test sleep 50
Running as unit sleep-50.service.

A: There are several ways to pause a process:

*

*Send a SIGSTOP to the the process to freeze it (SIGCONT to unfreeze). You can also hit Ctrl+S (Ctrl+Q) to send these signals to an active process. But if it is in background, you would have to use kill or its variations.

*Use nice to set priorities to processes. By default, all user processes are set to 10 and therefore get equal CPU. If the process is not important and can be slowed down - rise the niceness. If a process needs to have a priority - reduce the niceness.

*Just stop unneeded processes :)


text:
Q: How to click button "Save Configuration" after click button "Apply" in AppleScript How can I click button "Save Configuration" after click button "Apply" for save my VPN configuration in AppleScript on MacOs 10.11.

I tried:
click button "Apply" of window 1
click button "Save Configuration" of window 1

But command click button "Save Configuration" is not get it. Anyone has idea about it.
Thank you.


text:
Q: connecting POP3 via http proxy using HigLabo I'm using HigLabo to create an email client. Also I need to use an http proxy.
But authentication fails every time.
I found the base code here : .net pop3 over http proxy
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HigLabo.Net;
using HigLabo.Net.Pop3;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static Pop3Client pop;
        static Socket socket;

    static void Main(string[] args)
    {
        String proxyAddr = "112.241.212.104"; //This seemed to be working
        int proxyPort = 8585;
        byte[] buffer = new byte[25];

        pop = new Pop3Client("PopClient");
        socket = new Socket(AddressFamily.InterNetwork,
                                     SocketType.Stream,
                                     ProtocolType.Tcp);

        Console.WriteLine("Connecting to proxy...");
        socket.Connect(proxyAddr, proxyPort);
        Console.WriteLine("Connected to proxy");

        Console.WriteLine("Sending Packets...");
        socket.Send(Encoding.UTF8.GetBytes("CONNECT pop.mail.yahoo.com:995 HTTP/1.1<CR><LF>"));
        socket.Send(Encoding.UTF8.GetBytes("<CR><LF>"));
        Console.WriteLine("Packets sent");

        Console.WriteLine("Waiting for response...");
        socket.Receive(buffer);
        Console.WriteLine("Packets received");
        Console.WriteLine("Time Elapsed : " + timeElapsed + " seconds");

        Console.WriteLine("Connectong POP to socket...");
        if (pop.Connect(socket))
        {
            pop.Connect();
            Console.WriteLine("Connection completed");
        }
        else
        {
            Console.WriteLine("Disconnected");
            Disconnect();
            return;
        }

        pop.Ssl = true;
        pop.UserName = "EMAIL_ADDRESS";
        pop.Password = "PASSWORD";
        pop.ServerName = "pop.gmail.com";
        pop.Port = 995;

        Console.WriteLine("Authenticating...");
        if (pop.Authenticate())
        {
            Console.WriteLine("Authentication completed"); //Never comes here
            GetMail();
        }
        else
        {
            Console.WriteLine("Authentication failed"); //Always comes here
            Disconnect();
        }

    }

    private static void GetMail()
    {
        HigLabo.Mime.MailMessage msg = pop.GetMessage(1);
        Console.WriteLine(msg.BodyText);
    }

    static void Disconnect()
    {
        Console.WriteLine("Disconnecting...");
        pop.Close();
        socket.Close();
        Console.WriteLine("Disconnected");
    }
}

}
I gave permission for the app also.
What is wrong here?
Are there any other/better/easy ways to do this? May be with a different library?

A: This is wrong: <CR><LF>.
What you want to use is \r\n in your strings.


text:
Q: Mysql select rows based on previous quarterly month from current month I want to query row to view registered record based on previous quarterly month, for example:
current month / year: Jan 2018
the query should show all records by registered month which is: Oct 2017, Jul 2017, Apr 2017 and so on.
I use below query but only can select rows for last 3 month.
SELECT name, date, amount, agreement, bank
FROM `account`
WHERE (YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 3 MONTH) AND MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 3 MONTH))

A: You can do arithmetic like this:
select a.*
from account a
where mod(month(date), 3) = mod(month(current_date), 3);

You seem to understand how to handle the year component, but something like:
and date >= curdate() - interval 1 year

A: Try This One, Manually
select *
from account
Where current_date >= dateadd(year, -1, Getdate())
    And Month(current_date) In (
            Month(Getdate()),
            (Case When Month(Getdate())+3 > 12 Then Month(Getdate())+3-12 Else Month(Getdate())+3 End),
            (Case When Month(Getdate())+6 > 12 Then Month(Getdate())+6-12 Else Month(Getdate())+6 End),
            (Case When Month(Getdate())+9 > 12 Then Month(Getdate())+9-12 Else Month(Getdate())+9 End)
            )


text:
Q: Strip out all   from the excerpt in WP I have the following code in my WP functions.php file:
function custom_excerpt($new_length = 22, $new_more = ' ...') {

add_filter('excerpt_length', function () use ($new_length) {
return $new_length;
}, 999);

add_filter('excerpt_more', function () use ($new_more) {
return $new_more;
});

$output = get_the_excerpt();
$output = apply_filters('wptexturize', $output);
$output = apply_filters('convert_chars', $output);
$output = '<p>' . $output . '</p>';
echo $output;
}

I than use the following code to displat it:
 php custom_excerpt(50, ' ...');

My question is: How to get rid of all the "nbsp;" entities from all my excerpts on my WP page?


text:
Q: Fastlane export ipa fail I am trying to use Fastlane to do a CI job for generate iPA file.
The archived file are generated successfully. But for the export part I can't make it work.
The error is like:
        error: exportArchive: test1.framework does not support provisioning profiles.

        Error Domain=IDEProvisioningErrorDomain Code=10 "test1.framework does
not support provisioning profiles." UserInfo={IDEDistributionIssueSeverity=3,
    NSLocalizedDescription= test1.framework does not support provisioning profiles.,
     NSLocalizedRecoverySuggestion= test1.framework does not
support provisioning profiles, but provisioning profile PROFILE_TEST1 has been manually specified.
Remove this item from the "provisioningProfiles" dictionary in your Export Options property list.}

I can understand the error, the framework doesn't support the profile. The thing is how could I remove it?
Here is my Fastfile
lane :beta do |options|

    name = get_provisioning_profile(
      force: false,
      app_identifier: "com.xxx.test1",
      filename: "PROFILE_test1.mobileprovision")

    update_app_identifier(
      xcodeproj: "MyProject.xcodeproj",
      plist_path: "./mainInfo.plist",
      app_identifier: "com.xxx.test1"
    )

    //Is this update_project_provisioning issue? I thought this line
    //only setup my com.xxx.test1 to profile PROFILE_TEST1, correct?

    update_project_provisioning(xcodeproj: "MyProject.xcodeproj")

    build_app(
      workspace: "MyProject.xcworkspace",
      output_directory: "./OutputFile",
      xcconfig: xcconfigPath,
        export_method: "enterprise",
        scheme: "MyProject"
      )

  end

I have tried to set the export_options -> provisioningProfiles to empty, but still the same error.
build_app(
          workspace: "MyProject.xcworkspace",
          output_directory: "./OutputFile",
          xcconfig: xcconfigPath,
            export_method: "enterprise",
            scheme: "MyProject",
          export_options: {
             provisioningProfiles: {
               "com.xxx.framework1" => "",
               "com.xxx.framework2" => "",
             }
          })

EDIT
With this setup:
build_app(
          workspace: "MyProject.xcworkspace",
          output_directory: "./OutputFile",
          xcconfig: xcconfigPath,
            export_method: "enterprise",
            scheme: "MyProject"
          )

The output is:
: ▸ Archive Succeeded
[19:03:09]: Generated plist file with the following values:
[19:03:09]: ▸ -----------------------------------------
[19:03:09]: ▸ {
[19:03:09]: ▸   "provisioningProfiles": {
[19:03:09]: ▸     "com.xxx/test1": "PROFILE_TEST1"
[19:03:09]: ▸   },
[19:03:09]: ▸   "method": "enterprise",
[19:03:09]: ▸   "signingStyle": "manual"
[19:03:09]: ▸ }
[19:03:09]: ▸ -----------------------------------------

Any part on my Fastfile setup wrong?
How could I set to the profile None for the framework target?
Appreciate for any help?
EDIT
If I remove xcconfig option from build_app it works correct. If set it prompt the errors above.


text:
Q: How to make a css animation synchronized with the finger swipe in ionic? I'm trying to make a 3D annimation in ionic inspired from this tutorial.
The annimation works fine on drag Left, but it's not synchronized with my finger swipe.
I want to make it move progressively with the swipe, and, to make to the animation continue and finishes to its final state after a certain value otherwise it return to the initial state (if I did not reach this value when I release my finger).
Here my style.css file :
.view2 {
width: 100%;
height: 350px;
margins: 10px;
float: left;
position: relative;
border: 8px solid #fff;
box-shadow: 1px 1px 2px rgba(0,0,0,0.05);
background: #333;
-webkit-perspective: 1050px;
perspective: 1050px;
}
.view2 .slice{
width: 20.1%;
height: 100%;
z-index: 100;
background-color: red;
background-repeat: no-repeat;
background-position: center;
-webkit-background-size: cover;
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
-webkit-transform-origin: left center;
transform-origin: left center;
-webkit-transition: -webkit-transform 150ms ease-in-out;
transition: transform 150ms ease-in-out;
}
.view2 .slice div{
width: 100%;
}
.view2 div.view2-back{
width: 50%;
height: 100%;
position: absolute;
right: 0;
background: #666;
z-index: 0;
}
.view2 .s1 {
background-position: 0px 0px;
}
.view2 .overlay {
width: 100%;
height: 100%;
opacity: 0;
position: absolute;
-webkit-transition: opacity 150ms ease-in-out;
transition: opacity 150ms ease-in-out;
}
.view2 img {
position: absolute;
z-index: 0;
-webkit-transition: left 0.3s ease-in-out;
transition: left 0.3s ease-in-out;
}
.view2 div {
-webkit-transition: all 150ms ease-in-out;
transition: all 150ms ease-in-out;
}
.view2 .s2 > .overlay {
background: -webkit-linear-gradient(right, rgba(0,0,0,0.05) 0%,rgba(0,0,0,0) 100%);
background: linear-gradient(right, rgba(0,0,0,0.05) 0%,rgba(0,0,0,0) 100%);
}
.view2 .s3 > .overlay {
background: -webkit-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255, 255, 255, 0.2) 100%);
background: linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255, 255, 255, 0.2) 100%);
}
.view2 .s4 > .overlay {
background: -webkit-linear-gradient(right, rgba(0,0,0,0.8) 0%,rgba(0,0,0,0.2) 100%);
background: linear-gradient(right, rgba(0,0,0,0.6) 0%,rgba(0,0,0,0.2) 100%);
}
.view2 .s5 > .overlay {
background: -webkit-linear-gradient(left, rgba(0,0,0,0.8) 0%,rgba(0,0,0,0) 100%);
background: linear-gradient(left, rgba(0,0,0,0.8) 0%,rgba(0,0,0,0) 100%);
}
.view2 div.view2-back{
background: #0a0a0a;
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#0a0a0a), color-stop(100%,#666666));
background: -webkit-linear-gradient(left, #0a0a0a 0%,#666666 100%);
background: linear-gradient(left, #0a0a0a 0%,#666666 100%);
}

Here is my controller :
angular.module('starter.controllers', [])
.controller('HoverEffectCtrl', function($scope,$ionicModal) {
  angular.element(document).ready(function() {
    var $item   = $('.view2'),
    img     = $item.children( 'img' ).attr( 'src' ),
    width = $item.width()/5,
    struct  = '
';
    struct  +='
';
    struct  +='
';
    struct  +='
';
    struct  +='
';
    struct  +='
';
    struct  +='
';
    struct  +='
';
    struct  +='
';
    struct  +='
';
    var $struct = $( struct );
    $item.find( 'img' ).remove().end().append( $struct ).find( 'div.slice' ).css( 'background-image', 'url(' + img + ')' ).prepend( $( '' ) );
    $item.find( '.s2' ).css( 'transform', 'translateX('+width+'px)');
    $item.find( '.s2' ).css( 'background-position', '-'+width+'px 0px');
    $item.find( '.s3' ).css( 'transform', 'translateX('+width+'px)');
    $item.find( '.s3' ).css( 'background-position', '-'+2*width+'px 0px');
    $item.find( '.s4' ).css( 'transform', 'translateX('+width+'px)');
    $item.find( '.s4' ).css( 'background-position', '-'+3*width+'px 0px');
    $item.find( '.s5' ).css( 'transform', 'translateX('+width+'px)');
    $item.find( '.s5' ).css( 'background-position', '-'+4*width+'px 0px');
    $scope.swipeOff = function () {
      $item.find( '.s3' ).css( 'transform', 'translateX('+width+'px)');
      $item.find( '.s4' ).css( 'transform', 'translateX('+width+'px)');
      $item.find( '.s5' ).css( 'transform', 'translateX('+width+'px)');
      $item.find( '.overlay' ).css( 'opacity', 0);
    };
    $scope.swipeOn = function () {
      $item.find( '.overlay' ).css( 'opacity', 1);
      $item.find( '.s3' ).css( 'transform', 'translate3d('+width+'px,0,0) rotate3d(0,1,0,-55deg)');
      $item.find( '.s4' ).css( 'transform', 'translate3d('+width+'px,0,0) rotate3d(0,1,0,110deg)');
      $item.find( '.s5' ).css( 'transform', 'translate3d('+width+'px,0,0) rotate3d(0,1,0,-110deg)');
    };
  });
})

And here is the html :

A: I solved the problem by passing the $event object as an argument when calling the function swipeOn().
The $event object contains the browser's event object, including the gesture proprieties which contains the swipe variation $event.gesture.deltaX, the changes are :
In my controller :
const pi = Math.acos(-1);
const r = width;

$scope.swipeOff = function (event) {
  var dx = -$event.gesture.deltaX;
  if (dx >= 2.5*width) {
    finishAnimation();
  }
  else {
    $item.find( '.s3' ).css( 'transform', 'translateX('+width+'px)');
    $item.find( '.s4' ).css( 'transform', 'translateX('+width+'px)');
    $item.find( '.s5' ).css( 'transform', 'translateX('+width+'px)');
    $item.find( '.overlay' ).css( 'opacity', 0);
  }

};

$scope.swipeOn = function (event) {
  var dx = -$event.gesture.deltaX/3;
  var cosTeta = ((r - dx)) / r;
  var dTetaRad = Math.acos (cosTeta);
  var dTetaDeg = mTeta * (180/pi);
  if (dTetaDeg < 80) {
   $item.find( '.overlay' ).css( 'opacity', dTetaRad);
  $item.find( '.s3' ).css( 'transform', 'translateX('+width+'px) rotate3d(0,1,0,'+-dTetaDeg+'deg)');
  $item.find( '.s4' ).css( 'transform', 'translateX('+width+'px) rotate3d(0,1,0,'+2*dTetaDeg+'deg)');
  $item.find( '.s5' ).css( 'transform', 'translateX('+width+'px) rotate3d(0,1,0,'+-2*dTetaDeg+'deg)');
}
};

finishAnimation = function(){
  $item.find( '.overlay' ).css( 'opacity', 1);
  $item.find( '.s3' ).css( 'transform', 'translateX('+width+'px) rotate3d(0,1,0,-80deg)');
  $item.find( '.s4' ).css( 'transform', 'translateX('+width+'px) rotate3d(0,1,0,160deg)');
  $item.find( '.s5' ).css( 'transform', 'translateX('+width+'px) rotate3d(0,1,0,-160deg)');
};

In the HTML :


text:
Q: Memory leaks from Multidimensional array: NSMutableArray, NSArray, addObject and insertObjectAtIndex I've been working with this code for a couple of days trying to determine the cause of some memory leaks.  Pretty much every line after the "for loop" is generating memory leak percentages in the leak performance tool.
I've been trying a variety of permutations to get it to work.
This is the code I'm running now to try and get to the bottom of it:
-(void)populateArrays
{
    NSArray *arrTempSorted;
    [arrContacts removeAllObjects];
    [arrZzoneContacts removeAllObjects];
    [arrNormalContacts removeAllObjects];

    for( int i = 0 ; i < 200 ; i++ )
    {
        [arrZzoneContacts addObject:[[[NSArray alloc] initWithObjects: [NSNumber numberWithInt:1], @"Composite Name", @"YES", @"first name", @"last name", @"first", nil] autorelease]];
        [arrNormalContacts insertObject:[[[NSArray alloc] initWithObjects: [NSNumber numberWithInt:1], @"Composite Name", @"YES", @"first name", @"last name", @"first", nil] autorelease] atIndex:[arrNormalContacts count]];
        [arrContacts addObject:[[[NSArray alloc] initWithObjects: [NSNumber numberWithInt:1], @"Composite Name", @"YES", @"first name", @"last name", @"first", nil] autorelease]];
    }

    arrTempSorted = [arrContacts sortedArrayUsingFunction:order context:NULL];
    arrContacts = [arrTempSorted mutableCopy];

    arrTempSorted = [arrZzoneContacts sortedArrayUsingFunction:order context:NULL];
    arrZzoneContacts = [arrTempSorted mutableCopy];

    arrTempSorted = [arrNormalContacts sortedArrayUsingFunction:order context:NULL];
    arrNormalContacts = [arrTempSorted mutableCopy];

    //[arrTempSorted release];

}

The arrays and function are in the appDelegate.h file.  The arrays are initialized like so:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Global variables
    arrContacts = [[NSMutableArray alloc] init];
    arrZzoneContacts = [[NSMutableArray alloc] init];
    arrNormalContacts = [[NSMutableArray alloc] init];

    // Override point for customization after application launch.
    [window addSubview:tabBarController.view];
    [self.window makeKeyAndVisible];

    return YES;
}

I've tried the method of declaring an array in didFinishLaunchingWithOptions then assigning it to the arrContacts (for example) and then releasing it but I get "bad access" errors when we get to the populateArrays method.
Any insight would be greatly appreciated and please let me know if I can provide greater detail

A: You are allocating memory for arrContacts, arrZzoneContacts, and arrNormalContacts in your second code excerpt.  Then, after your for loop, you are allocating more memory for different instances of NSMutableArray by copying arrTempSorted.  When you assign those new instances to your arrContacts, arrZzoneContacts, and arrNormalContacts variables, you are losing your reference to the memory you originally allocated for them, so you no longer have the opportunity to release it, hence the leak.
When you copy something, you are creating a new instance.  If all you are doing with those variables is storing a copy, then you don't need to allocate the instance in the first place, copy does it for you.  If you do actually need that original instance, then release it before reassigning to those variables.
For more information, see the Memory Management Programming Guide.

A: As Jim mentioned, you're overwriting your arrContacts array (and the other arrays) which is causing the leak.
As a side note though, you can avoid this problem entirely because your arrContacts (and other arrays) are already mutable. The -sortedArrayUsingFunction:context method is part of the NSArray class and it returns a non-mutable array with the results. However, NSMutableArray has a method called -sortUsingFunction:context which will do the exact same sorting but it will do it in place and just update the arrContacts array itself. No need to copy to and from other arrays.


text:
Q: Modal close clicking outside the content Can someone please help me? I need to be able to close this modal when I click outside the content; this is my code:

$(document).ready(function(){
    $(".add-roles-btn").click(function(){
       $("#modal1").addClass("show-modal");
    });

});
.overlay {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(50, 65, 97, 0.5);
  z-index: 9999;
  opacity: 0;
  visibility: hidden;
  transition: all .3s; }
  .overlay .cancel {
    position: absolute;
    width: 100%;
    height: 100%;
    cursor: default; }
  .overlay__content {
    position: absolute;
    top: 44%;
    left: 55.5%;
    padding: 4.8rem 6.4rem;
    width: 540px;
    background-color: #ffffff;
    box-shadow: 0 2rem 4rem rgba(81, 136, 255, 0.2);
    border-radius: 3px;
    display: table;
    overflow: hidden;
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.25);
    transition: all .4s .2s; }
    @media only screen and (max-width: 61.875em) {
      .overlay__content {
        top: 50%;
        left: 50%; } }
    @media only screen and (max-width: 47em) {
      .overlay__content {
        padding: 4rem 6.5rem;
        width: 500px; } }
    @media only screen and (max-width: 37.5em) {
      .overlay__content {
        padding: 4rem 6.5rem;
        width: 100%; } }

 .show-modal {
  opacity: 1;
  visibility: visible; }

 .show-modal .overlay__content {
  opacity: 1;
  transform: translate(-50%, -50%) scale(1); }
 <button type="button" class="add-roles-btn">addAdd roles</button>

Add role

                    <form action="#">

                        <input type="text" class="form__input" id="role_title">
                        Role Title

                        <textarea name="" class="form__input resize-none u-margin-bottom-0" id="role_description" rows="5"></textarea>
                        Role Description

                            <button class="btn btn--primary capitalize add-role-btn">Add Role add</button>

                    </form>

As you can see it has the JS code on click it shows the modal, but I am not able to change it when you click outside to be closed; how can this be done? I have created this from scratch. I do not want to use some library or something; can you help me? I am new on JavaScript and coding on general. I would really appreciate it; thank you.

A: You stated you don't want to use any library so here's a vanilla JS solution.
To provide that, I also "translated" your jQuery code to vanilla JS:
document.getElementsByClassName('add-roles-btn')[0].onclick = function() {
    document.getElementById('modal1').classList.add('show-modal');
}

// This block hides the modal when the user clicks outside of it
window.onclick = function(event) {
    if (event.target == document.getElementById('modal1')) {
    document.getElementById('modal1').style.display = 'none';
  }
}

Here's a working example with the rest of your code.

If you want the ability to re-open it, this should work:
var modal = document.getElementById('modal1');

document.getElementsByClassName('add-roles-btn')[0].onclick = function() {
    modal.classList.add('show-modal');
}

window.onclick = function(event) {
    if (event.target == modal) {
    modal.classList.remove('show-modal');
  }
}

Here's the updated code.

A: Here is the updated code, basically the concept was listening to click events on the body and if the DOM parent chain on the element doesn't reach the modal modal1 - the click is outside of it and therefore the modal can be closed.
Another important note was calling e.stopPropagation as the body event would be called after the button event, causing the window to be closed. Calling e.stopPropgation would mean that when the button is clicked, the "larger" body event won't trigger.
$(document).ready(function(){
    $(".add-roles-btn").click(function(e){
       $("#modal1").addClass("show-modal");
       // This is required so that when clicking the button the click event wont propogate to the body event
       e.stopPropagation()
    });
    // This function listens to all clicks on the document and gets the event data e
    $('body').click(function(e) {
       target = e.target;
       // If the clicked target isnt under modal1 - that means it won't be found in its parents
       if (($(target)).parents('#modal1').length == 0) {
          $("#modal1").removeClass("show-modal");
       }
    })
});

$(document).ready(function(){
    $(".add-roles-btn").click(function(e){
       $("#modal1").addClass("show-modal");
       // This is required so that when clicking the button the click event wont propogate to the body event
       e.stopPropagation()
    });
    // This function listens to all clicks on the document and gets the event data e
    $('body').click(function(e) {
       target = e.target;
       // If the clicked target isnt under modal1 - that means it won't be found in its parents
       if (($(target)).parents('#modal1').length == 0) {
          $("#modal1").removeClass("show-modal");
       }
    })
});
.overlay {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(50, 65, 97, 0.5);
  z-index: 9999;
  opacity: 0;
  visibility: hidden;
  transition: all .3s; }
  .overlay .cancel {
    position: absolute;
    width: 100%;
    height: 100%;
    cursor: default; }
  .overlay__content {
    position: absolute;
    top: 44%;
    left: 55.5%;
    padding: 4.8rem 6.4rem;
    width: 540px;
    background-color: #ffffff;
    box-shadow: 0 2rem 4rem rgba(81, 136, 255, 0.2);
    border-radius: 3px;
    display: table;
    overflow: hidden;
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.25);
    transition: all .4s .2s; }
    @media only screen and (max-width: 61.875em) {
      .overlay__content {
        top: 50%;
        left: 50%; } }
    @media only screen and (max-width: 47em) {
      .overlay__content {
        padding: 4rem 6.5rem;
        width: 500px; } }
    @media only screen and (max-width: 37.5em) {
      .overlay__content {
        padding: 4rem 6.5rem;
        width: 100%; } }

 .show-modal {
  opacity: 1;
  visibility: visible; }

 .show-modal .overlay__content {
  opacity: 1;
  transform: translate(-50%, -50%) scale(1); }

<button type="button" class="add-roles-btn">addAdd roles</button>

Add role

                    <form action="#">

                        <input type="text" class="form__input" id="role_title">
                        Role Title

                        <textarea name="" class="form__input resize-none u-margin-bottom-0" id="role_description" rows="5"></textarea>
                        Role Description

                            <button class="btn btn--primary capitalize add-role-btn">Add Role add</button>

                    </form>


text:
Q: JItterBit HTTP Endpoint I am working to set up a HTTP Endpoint in JitterBit, for this end point we have a system that will call this Endpoint and pass parameters through the URL to it.
example...
http://[server]:[server port]/EndPoint?Id={SalesForecID}&Status={updated status in SF}
Would i need to use the Text File, JSON or XML Method for this? Follow up question would be if it is JSON or XML what would the file look like that is uploaded during creating the endpoint. I have tired with no success with the text file version.
any help would be great.

A: I'm just seeing your question now.  You may have found a solution, but this took me a while to figure out, so I'll respond anyway.
To get the passed values, go ahead and create your HTTP Endpoint and add a new operation triggered by it.  Then, in your new operation create a script with something like the following:
$SalesForceID = $jitterbit.networking.http.query.Id
$UpdatedStatus = $jitterbit.networking.http.query.Status
You can then use these variables elsewhere in your operation chain.
If you want to use these values to feed into another RESTful web service (i.e. an HTTP Source), you'll have to create a separate transformation operation with the HTTP Source.  You'd set that source URL to be:  http://mysfapp.com/call?Id=[SalesForceID]&Status=[UpdatedStatus].  I'm not sure why, but you can't have the script that extracts the parameters from the Endpoint and the HTTP Source that uses those in the same operation.
Cheers


text:
Q: How to bring table values into temp table I have a sql query where SQL Server outputs  data to looks like this

ScheduledAppts
KeptAppts
UnkeptAppts

30
20
10

And  I want to alter this output into a sql server #temp table so it looks like this:

Category
Count

ScheduledAppts
30

KeptAppts
20

UnkeptAppts
10

Been trying to use Pivot but I think I'm doing it wrong.
Code:
SELECT

         COUNT(x.Scheduled) AS ScheduledAppts,

         COUNT(x.KeptEncounters) AS KeptAppts,

         COUNT(x.UnkeptEncounters) AS UnkeptAppts

   FROM (

         SELECT DISTINCT

                  COUNT(frz.TotalAppt) AS Scheduled,

                  CASE

                       WHEN frz.PDEncounters > 0 THEN

                       COUNT(frz.PDEncounters)

                  END AS KeptEncounters,

                  CASE

                       WHEN frz.PDEncounters = 0 THEN

                       COUNT(frz.PDEncounters)

                  END AS UnkeptEncounters,

           FROM [CDW].[dbo].[Fact_FREEZEPOLICE] frz

   ) x

A: You actually want to UNPIVOT here -
DECLARE @T TABLE (ScheduledAppts INT, KeptAppts INT, UnkeptAppts INT)

INSERT INTO @T (ScheduledAppts, KeptAppts, UnkeptAppts)
SELECT 30, 20, 10

SELECT [Category]
    ,[Count]
FROM (
    SELECT ScheduledAppts
        ,KeptAppts
        ,UnkeptAppts
    FROM @T
    ) P
UNPIVOT([Count] FOR [Category] IN (
            ScheduledAppts
            ,KeptAppts
            ,UnkeptAppts
            )) AS UnPvt

Output:

Category
Count

ScheduledAppts
30

KeptAppts
20

UnkeptAppts
10

Reference: Converting Columns into rows with their respective data in sql server

A: You can use cross apply:
select v.*
from output o cross apply
     (values ('ScheduledAppts', ScheduledAppts),
             ('KeptAppts', KeptAppts),
             ('UnkeptAppts', UnkeptAppts)
     ) v(category, count);

Note:  You might find it simpler to change the original query, if the original "table" is really a query result.


text:
Q: ADB touchevent does not work dependent on computer I have a few questions on ADB.
I try to run the following batch file:
adb wait-for-devices
adb shell sendevent /dev/input/event9 3 53 67
adb shell sendevent /dev/input/event9 3 54 768
adb shell sendevent /dev/input/event9 3 48 40
adb shell sendevent /dev/input/event9 3 50 4
adb shell sendevent /dev/input/event9 3 57 0
adb shell sendevent /dev/input/event9 0 2 0
adb shell sendevent /dev/input/event9 0 0 0
adb shell sendevent /dev/input/event9 3 53 67
adb shell sendevent /dev/input/event9 3 54 768
adb shell sendevent /dev/input/event9 3 48 0
adb shell sendevent /dev/input/event9 3 50 4
adb shell sendevent /dev/input/event9 3 57 0
adb shell sendevent /dev/input/event9 0 2 0
adb shell sendevent /dev/input/event9 0 0 0

adb shell input keyevent 8
adb shell input keyevent 9
adb shell input keyevent 10
adb shell input keyevent 11
adb shell input keyevent 12

adb shell input keyevent 5

*

*first part deals with getting to the dialer via touchevents
(I did not find a keyevent for this)

*second part types 1,2,3,4,5 via keyevents

*third part presses the call button via keyevent

If I run this script with the connected cellphone on my computer here, the touchevents
are replayed correctly and 12345 is called.
If I connect it to a different PC, the first part does not bring me to the dial screen
for some reason?
What could be the reason, that my code runs on one computer and not on the other?
Is there another way to emulate finger sweeps except for touchevents?
EDIT:
It seems, that the connection is a little slow on the pc, where it works not as good.
ADB versions are the same and actually I was able to make the behavior run by changing the script.
Now I see, that when I create touchevents e.g. for a sweeping action.
These are many events.
When I then input them one by one using the command adb shell sendevent as above.
I can observe on the cellphone, that the sweeping is really really slow.
Is there a way somehow to pipe the commands directly into adb such, that
the reaction is as fast as with a normal finger sweep?

A: Just to dial a number you can always use service call phone 2 s16 "12345"

A: Also in the recent Android versions you can use input tap and input swipe commands
usage: input ...
       input text <string>
       input keyevent <key code number or name>
       input tap <x> <y>
       input swipe <x1> <y1> <x2> <y2>

A: Proceeding as shell/ batch scripting to direct commands to adb shell
solved the problem.
The actual problem was, that calling the adb shell for each command
takes a lot of time.
This results in lagged execution and conflicts occur because of this timing issue.