text:
Q: How to create aligned table for the GitHub wiki? I am auto-generating the description wiki pages for my class. The thing is when the table is displayed, it automatically inserts some new lines, which brakes the function/method definition. For example setFSensor is:
E
:setFSensor(
V, V, N)

And it must be: E:setFSensor( V, V, N)
How can I make GitHub to display my custom table properly?

A: To overall control the width of the table column, I've put dots instead of underscores, dashes, and spaces. The name Test API extended becomes ...Test.API... as a workaround.


text:
Q: Dynamically added ng-form and validation I have a directive with template containing ng-form:
<ng-form name="autocompleteForm">

    <input type="text" class="form-control" ng-model="ctrl.val.value" name="autocompleteField" required>

      Please, select the value

</ng-form>

And i add this form dynamically using ng-repeat. Everything - form itself, validation - works, but there is one annoying thing: after form is added it's $invalid and error message is shown. Not sure why it's happening and how to fix this. Here is forms's object after form is added:
{
   "$error":{
      "required":[
         {
            "$validators":{

            },
            "$asyncValidators":{

            },
            "$parsers":[

            ],
            "$formatters":[
               null
            ],
            "$viewChangeListeners":[

            ],
            "$untouched":true,
            "$touched":false,
            "$pristine":true,
            "$dirty":false,
            "$valid":false,
            "$invalid":true,
            "$error":{
               "required":true
            },
            "$name":"autocompleteField",
            "$options":null
         }
      ]
   },
   "$name":"autocompleteForm",
   "$dirty":false,
   "$pristine":true,
   "$valid":false,
   "$invalid":true,
   "$submitted":false,
   "autocompleteField":{
      "$validators":{

      },
      "$asyncValidators":{

      },
      "$parsers":[

      ],
      "$formatters":[
         null
      ],
      "$viewChangeListeners":[

      ],
      "$untouched":true,
      "$touched":false,
      "$pristine":true,
      "$dirty":false,
      "$valid":false,
      "$invalid":true,
      "$error":{
         "required":true
      },
      "$name":"autocompleteField",
      "$options":null
   }
}

Found some blogs writing about dynamically added forms (like this one) and they have same behavior also. Is this default angular's way to go? Or there are some options to prevent "initial validation"?

A: You could add the ng-if directive on your messages container to only show it if the form has been submitted like so:

    Please, select the value

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieving external XML file with fetch in JS I'm trying to retrieve XML data from the URL below with Javascript and later parse the data I want from it.  I've set up the fetch request below.  My browser shows I'm receiving the yield.xml file, but I'm not able to access it.  Instead, I get the error:
scripts.js:149 Uncaught (in promise) TypeError: Cannot read property 'getElementsByTagName' of undefined
    at scripts.js:149
(anonymous) @   scripts.js:149

Any help would be appreciated

function yield() {
  var url = "https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Datasets/yield.xml";
  var myHeaders = new Headers();
  myHeaders.append('Content-Type', 'text/plain');
  fetch(url, {
    headers: myHeaders,
    mode: "no-cors",
  }).then(function(response) {
    console.log(response);
    var xmlDoc = response.responseXML;
    var bc1month = xmlDoc.getElementsByTagName("BC_1MONTH").nodeValue;
    console.log(bc1month);
  });
}

Image of network tab showing yield.xml file and contents


text:
Q: Selecionar registro que possui um campo date usando apenas o ano no where Como posso fazer um SELECT no banco de dados no qual os registros possuem um campo que o formato é DATE Ex:(2017-05-15) e na clausula WHERE eu quero por apenas o ano. Tambem queria saber se é melhor usar as datas no banco de dados em formato varchar ou no formato date mesmo.

A: Você pode usar a função Year:
SELECT * from tabela WHERE YEAR(campo_data) = '2017'

Ou Extract:
SELECT * from tabela WHERE EXTRACT(YEAR FROM campo_data) = '2017'

Se é melhor usar Date ou Varchar vai depender da necessidade, o tipo de dado infere nos recursos que estarão disponíveis. A vantagem de usar o Date é que funções específicas de data podem ser úteis, como a usada acima.

A: Você também pode declarar em uma variável o ano atual, exemplo:
$data = date('Y');

Depois e só jogar no where!


text:
Q: Identify the degree , Minutes and seconds from coordinates I have coordinates which has degree format, i want to convert it into decimal format,
For this i want to grab Degree , Minutes and seconds from coordinates.
Standard format is DDMMSS N / DDMMSS E , But i have one special type of  coordinates.
The coordinate is :
4729N00937E , 472027N0114441E , 472116N0114328E , 4729N00937E

I wan to convert it into decimal format ,  I want to use in Geojson.

A: As you already stated in your comment, these are coordinates from a NOTAM (Notice To Airmen). The values are already in degree, minute and seconds using the format DDMMSSNDDDMMSSE or DDMMNDDDMME.
See also the following examples:
472027N0114441E --> 47°20'27''N 011°44'41''E

In case the seconds are zero, these are ommitted from the notation:
4729N00937E --> 47°29'00''N 009°37'00''E


text:
Q: IndexOutOfBoundsException при добавлении элемента в ArrayList Если список reddots:
ArrayList<Red> reddots =  new ArrayList();

В него добавляются элементы:
class DotListener extends InputListener {
    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button){
        event.getListenerActor().remove();
        float xx = event.getListenerActor().getX();
        float yy = event.getListenerActor().getY();
        int ind = ((int)xx - 46) / 69;
        if (count % 2 == 0) {
            Red r = new Red();
            r.setSize(30, 30);
            r.setPosition(xx, yy);
            r.setColor(Color.RED);
            reddots.add(ind, r);
            stage.addActor(r);
        } else {
            Blue b = new Blue();
            b.setSize(30, 30);
            b.setPosition(xx, yy);
            b.setColor(Color.BLUE);
            stage.addActor(b);
        }
        count++;
        return true;
    }
}

Почему код крашится? Если убрать reddots.add(ind, r), то крашиться не будет. Но мне нужно давать индекс каждой точке.
Классы Red и Blue наследуются от Dot.
Класс Dot:
class Dot extends Actor { //invisible
    @Override
    public void draw(Batch batch, float parentAlpha) {
        Color batchColor = batch.getColor();
        final float r = batchColor.r;
        final float g = batchColor.g;
        final float b = batchColor.b;
        final float a = batchColor.a;
        Color dotColor = getColor();
        batch.setColor(dotColor.r, dotColor.g, dotColor.b, dotColor.a * parentAlpha);
        batch.draw(dotimg, getX(), getY(), getWidth(), getHeight());
        batch.setColor(r, g, b, a);
    }
}

Ошибка в консоли:

E/AndroidRuntime: FATAL EXCEPTION: GLThread 151
                    Process: com.mygdx.game, PID: 2941
                    java.lang.IndexOutOfBoundsException: Index: 9, Size: 0
                        at java.util.ArrayList.add(ArrayList.java:457)
                        at com.mygdx.game.MyGdxGame$DotListener.touchDown(MyGdxGame.java:48)
                        at com.badlogic.gdx.scenes.scene2d.InputListener.handle(InputListener.java:56)
                        at com.badlogic.gdx.scenes.scene2d.Actor.notify(Actor.java:182)
                        at com.badlogic.gdx.scenes.scene2d.Actor.fire(Actor.java:147)
                        at com.badlogic.gdx.scenes.scene2d.Stage.touchDown(Stage.java:282)
                        at com.badlogic.gdx.backends.android.AndroidInput.processEvents(AndroidInput.java:375)
                        at com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:457)
                        at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1548)
                        at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1259)
  E/AndroidGraphics: waiting for pause synchronization took too long; assuming deadlock and killing

A: Вы создаёте пустой список:
ArrayList<Red> reddots = new ArrayList();

Размер (size) по умолчанию у него 0.
Когда вы пытаетесь добавить элемент в список на определённую позицию, происходит такая проверка:
if (index > size || index < 0)
    throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

Так как index в вашем случае равен 9 (судя по stacktrace), а размер - 0, то в итоге пробрасывается исключение.
Вариантов решения проблемы в данной ситуации как минимум два:

*

*Добавлять элементы не на конкретный индекс, а в конец списка:
reddots.add(r);

*Если всё же нужно добавлять на определённый индекс, то стоит позаботиться о размере списка при его создании:
int dotsCount = 1000;
Red[] dummy = new Red[dotsCount];
ArrayList<Red> reddots = new ArrayList<>(Arrays.asList(dummy));

На всякий случай уточню зачем городить такой код:

*

*Если просто создать ArrayList, задав ему initialCapacity, то size его по-прежнему будет 0 и IndexOutOfBoundsException снова появится.

*Если сделать List<Red> reddots = Arrays.asList(dummy);, то при попытке добавить элемент в список будет проброшено UnsupportedOperationException.


text:
Q: Could not resolve placeholder 'server.port' in value "${server.port}" After upgrading a jHipster project from version 4.14.5 to the version 5.8.1 I am getting this error when I try to run the application:

Exception encountered during context initialization - cancelling
  refresh attempt:
  org.springframework.beans.factory.BeanCreationException:  Error
  creating bean with name 'loggingConfiguration' defined  in file
  [\config\LoggingConfiguration.class]:
Unexpected exception during bean creation; nested exception is
  java.lang.IllegalArgumentException:  Could not resolve placeholder
  'server.port' in value "${server.port}"

Do you have any idea of what could be the cause of the problem?

A: Spring looks for placeholders specified inside the @Value annotation in various locations. Since you're probably running a Spring Boot application, you might want to check the documentation for externalized configuration.
I'd bet you did have it specified as a command line argument, or inside the application.properties resource file.
Btw, the . (dot) is not a problem.

A: I had the same issue, I solved this simply by adding the server.port property to application.properties
MultiplicationController.java
@Slf4j
@RestController
@RequestMapping("/multiplications")
@CrossOrigin(origins = "http://localhost:9090")
final class MultiplicationController {

    private final MultiplicationService multiplicationService;

    private final int serverPort;

    @Autowired
    public MultiplicationController(final MultiplicationService multiplicationService,
            @Value("${server.port}") int serverPort) {
        this.multiplicationService = multiplicationService;
        this.serverPort = serverPort;
    }

    @GetMapping("/random")
    public Multiplication getRandomMultiplication() {
        log.info("Generating a random multiplication from server @ {}", serverPort);
        return multiplicationService.createRandomMultiplication();
    }
}

application.properties
server.port=8080

A: I was just having the same issue.
It actually worked when I replaced the "."s with "_"
So my method :
@Value("${server_port")
Integer port;

and my properties.yml
server:
  port: 1234
server_port: 1234

Of course, the redundancy isn't ideal, but @Value seems to be unable to handle "."s.


text:
Q: $find() return null for defined ajax behaviour All,
Environment: ASP.NET 2.0, AjaxToolkit build 1.0.20229.0, IE9
I am using $find() to find a behaviour of a call out extender so I can show explicitly using .show() method. Unfortunately, $find() returns null.
 $find('my auto generated behvaiour Id').show();

FYI: The BehaviorID on the ValidatorCalloutExtender is generated using ClientID of the control (ClientID_ + "BehaviourID" <- is also what I use in my $find() function) because I have many instances of this control on the same page.
I looked at the rendered code and I can see JS to create that creates the behaviour:
Sys.Application.add_init(function() {
$create(AjaxControlToolkit.ValidatorCalloutBehavior ...

The $find() executes AFTER a postback in an UpdatePanel and returns always null.
EDIT (ADDED):
I created new page and below is the code, find() returns still null,- is there a bug in Ajax control tooklit for ASP.NET 2.0?
<body>
<form id="form1" runat="server">

<asp:ScriptManager ID="ScripManager1" runat="server" EnablePageMethods="True" >

        </asp:ScriptManager>

    <asp:TextBox runat="server" ID="txtInputField" />
    <asp:RequiredFieldValidator runat="server" ID="valInput"
ControlToValidate="txtInputField"
ErrorMessage="ERROR STRING"
Display="none" /> <ajaxToolkit:ValidatorCalloutExtender runat="server" ID="extValInput" TargetControlID="valInput" BehaviorID="myID" />
<asp:Button runat="server" ID="btn" OnClick="btn_click" CausesValidation="True" />

<script type="text/javascript">

        var obj = $find("myID");
        alert(obj);

</script>
</form>

ADDED:
After observation in JS debugger, I realized that the validator callout extender only appears (is added dynamically to the DOM) when there's error, hence, if there's no error you cannot find it.
THE QUESTION NOW IS: How to reposition the call out extender baloon before displaying it? It is really catch 22, you can't access it when it is not displayed and when it is displayed, it is already to late because it displays in the wrong place.

A: The cause of the problem is that you try to find component before page completes component initialization. Try to access your editor in Sys.Application.add_load event handler. I tried the following code and everything works fine:
<script type="text/javascript">
    Sys.Application.add_load(function() {
        var obj = $find("myID");
        alert(obj);
    });
</script>

Edit:
To address your latest question: how you can reposition it. Callout ValidatorCalloutExtender uses PopupExtender to show it. So, you can try to bind to 'showing' and 'shown' events of the popup extender and then try to reposition callout.
<script type="text/javascript">
    Sys.Application.add_load(function() {
        var callouotComponent = $find("myID");
        var popupBehavior = callouotComponent._popupBehavior;

        popupBehavior.add_showing(function(){alert("I am showing");});
        popupBehavior.add_shown(function(){alert("I was shown");});
    });
</script>

Note: I didn't verify this code, but it can be used as start point.

A: Modified your code and verified, popup position is changing.
<script type="text/javascript">
    Sys.Application.add_load(function () {
      var callouotComponent = $find("myID");
      //Below line is to init popup ballon, otherwise popup behaviour will return null
      callouotComponent._ensureCallout();
      var popupBehavior = callouotComponent._popupBehavior;
      popupBehavior.set_x(100);
      popupBehavior.set_y(100);
    });

</script>


text:
Q: wpf data template binding (Dynamically generating form) I want to dynamically generate a form in WPF. I would like to do it using XAML not from the code behind(Which I am currently doing.).
If I have a data template like below, What is the parent controller that I can use for this.(Like we use Listbox)
I have dataTemplate like below
<DataTemplate x:Key="FieldTemlate">
       <TextBlock HorizontalAlignment="Left"  VerticalAlignment="Top" />
       <TextBox  VerticalAlignment="Top"  Width="40" />
</DataTemplate>

A: ItemsControl is what you need.
Here you can find an example.


text:
Q: How do I map a local path to a drive letter in Windows 7? I am coding on something and want to map \cygwin\home\bob\code\ to U: drive letter. When I try to map it using net use C:\cygwin\home\bob\code\ U: /P:yes , but it gave the following error:
System error 67 has occurred
The network name cannot be found

But it's not actually a network path I'm trying to map. How do I do this?

A: Use vSubst. It is like the subst command line tool, but it has a UI and is persistent.

A: If it is only local what you need, try subst.
subst u: C:\cygwin\home\bob\code\

A: When you map drives they must be mapped to a SHARED network folder. You are trying to map to a local path, it won't work. Instead try sharing the Code folder then use this:

net use u: \\yourpcname\code /p:yes

A: The best way to do this across bootup is to put it in the registry. Open regedit.exe by pressing Win + R and typing regedit then hit Enter or click OK. Navigate to
HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ Session Manager \ DOS Devices
Add a new string that is a REG_SZ value.
Name it X: where X is your drive letter
The value should be the path you want mapped to that drive letter, in this form:
\DosDevices\C:\Folder\Example


text:
Q: How can I show that $D_{2n}$ follows from these relations? Suppose we have a group $A$ which is generated by generators $R$ and $F$, subject to the relation
$$ R^n=I, F^2=I,RF= FR^{-1}.$$
It should be just the dihedral group of order $2n$, the one generated by  $n$ rotations and 1 reflection.
I am a bit confused that how I show these relation will define $A$ to have exactly $2n$ elements.
I understand that there would be $I, R,\dots, R^{n-1}$ and $F,RF,\dots, R^{n-1}F$. But how can I show these elements are distinct. For example, how can I show $R\not= R^2F$. The notes I learned just says that if they are equal then we would have $F=R^4$ and it is not possible to get this using the relations. I am a bit worried here. How do you see that these relation does not imply $F=R^4$ or more generally $F= R^{k}$ for any $k$.
I guess this should be really basic but I don't see how.


text:
Q: intuit merchant services with opensource shopping cart Has anyone been able to integrate intuit's merchant services with any of the following shopping carts?

*

*Magento

*Zencart

*osCommerce

*virtuemart

*oscMAX

I am setting up a shopping cart site for a client and they want to use intuit merchant services. They also use Fishbowl inventory(also intuit). I wanted to ask and see if anyone has accomplished this (not buy purchasing integration software) and what the necessary steps would be. Would this require building my own intuit app using the api/sdk and shopping cart module?

A: I've done this for every shopping cart you listed above.
You will obviously have to do some coding- you'll have to write a gateway module for whatever shopping cart you're using. However, if you use the QuickBooks PHP DevKit, that should be pretty trivial to do. The actual QuickBooks Merchant Services specific code is as simple as:
// Create an instance of the MerchantService object
$MS = new QuickBooks_MerchantService(
    $dsn,
    $path_to_private_key_and_certificate,
    $application_login,
    $connection_ticket);

// Create the CreditCard object
$Card = new QuickBooks_MerchantService_CreditCard($name, $number, $expyear, $expmonth, $address, $postalcode, $cvv);

// We're going to authorize $295.00
$amount = 295.0;

if ($Transaction = $MS->authorize($Card, $amount))
{
   ... do something here ...
}

If you want to dive in to the more technical bits of it, you should refer to the QuickBooks Merchant Services documentation on Intuit's website:
QuickBooks Merchant Services documentation
We also have some additional PHP-specific information about QuickBooks Merchant Services on our website:
PHP + QuickBooks Merchant Services
If you get stuck/need help, contact me with the info in my profile- we have pre-built plugins for almost all of those shopping carts that we sell and support commercially.


text:
Q: Ajax Button to fetch data without refresh? I would like to know how a button submit can interact with AJAX to SELECT FROM data as a MySQL query without refreshing the page . I already have a text box interacting with AJAX so that the page does not refresh when the user inputs the text and presses enter but have no idea how to make the button do it my code below shows how im getting the text box to insert data without refreshing
Here is my script for the textbox

    About me<input type="text" id="name" placeholder="Type here and press Enter">

Here is the action
<?php

if (isset($_POST['name'])) {
echo '
'.$_POST['name'];

include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);

$name = $_POST['name'];
$name= mysqli_real_escape_string($con, $name);

$q = mysqli_query($con,"SELECT * FROM tbl1 WHERE username = '".$_COOKIE[$cookie_name]."'");

   while($row = mysqli_fetch_assoc($q)){
       //echo $row['id'];
       $id = $row['id'];
   }

$result=$con ->query=("REPLACE INTO about_user (about_me,number) VALUES ('".$name."','".$id."')");

$insert = $con->query($result);

echo "About Me Updated";
}

?>

Now all I need to do is have the below example of a button do something similar but instead of INSERTING just SELECT , how can i change the above script to allow a button to handle the action please?
<form

action="action_mail_view.php"   method="post">

<input type="submit" class="button" name='msubmit'  value="View Mail"/>

</form>

A:

function callServer() {
  $('#mail-button').on('click', function() {
    var info = $('#name').val();
    $.ajax({
      method: "POST",
      url: "about_me_action.php",
      data: {
        name: info
      },
      success: function(status) {
        $('#result').append(status);
        $('#name').val('');
      }
    });
  });

}

$(document).ready(function() {
  $('#name').focus();
  $('#name').keypress(function(event) {
    var key = (event.keyCode ? event.keyCode : event.which);
    if (key == 13) {
      $('#mail-button').trigger('click');
    };
  });
});
<form action="action_mail_view.php" method="post">

  <input type="submit" class="button" id="mail-button" name='msubmit' value="View Mail" />

</form>

A: You haven't showed us how you tried to make your button work so how can we give you feedback?  Basically you want a similar ajax call that calls action_mail_view.php using the GET method
Ajax
$.ajax({
    method: "GET",
    url: "action_mail_view.php",
    data: {},
    success: function(results) {
        var userinfo = JSON.parse(results);
        //Todo: do what you want with the user's info
    }
});

On the PHP side, you should first authenticate the user (not shown here), then SELECT her info from the DB and return it
action_mail_view.php
//Todo: authenticate

//this works with your setup, but it's a bad idea to trust
//a cookie value or anything else coming from the
//browser without verification
$username= mysqli_real_escape_string($con, $_COOKIE[$cookie_name]);

//get the user's info from your DB. By using a JOIN, we can execute
//just one query instead of two.
$sql = "SELECT t2.* FROM tbl1 as t1 "
        ."LEFT JOIN about_user as t2 "
        ."ON t1.id = t2.number"
        ."WHERE t1.username = $username";

//Todo: execute query. see what results you get and refine
//      the SELECT clause to get just what you want

if($q = mysqli_query($con,$sql)):
    $userinfo = mysqli_fetch_assoc($q);

    //tell the browser to expect JSON, and return result
    header('Content-Type: application/json');
    echo json_encode($userinfo);
else:
    //Todo: error handling
endif;


text:
Q: How best to refactor variable instantiation duplication in Java? I have two methods in Java that collect different information, but they both set up and run the same process which we then collect information from - and the collection of the data happens inside a loop, and the variables we instantiate are also used in the loop.
 Map<Integer, Integer> getResponsesWithCount(int baseCostMultiplier, int reels, int visibleSymbols, String stakeCostUuid, int totalBets) throws InsufficientFundsException {
    final int stake = getStake(baseCostMultiplier, stakeCostUuid);
    long balance = 10L * stake;
    final TestGpasPlatform testGpasPlatform = TestGpasPlatform.create(ryotaAdapter, TestGpasPlatform.DEFAULT_MIN_BET, Math.max(stake, TestGpasPlatform.DEFAULT_MAX_BET), TestGpasPlatform.DEFAULT_MAX_WIN, ImmutableList.of(baseCostMultiplier));

    final Map<Integer, Integer> responseCounts = new HashMap<>();
    for (int count = 0; count < totalBets; count++) {
        final Tuple2<List<Output>, TestGpasPlatform> result = playWithRealRng(baseCostMultiplier, count, reels, visibleSymbols, stakeCostUuid, testGpasPlatform);
        // If we run out of balance, re-start, we want to do meaningful spins that trigger features, etc
        balance = checkBalance(stake, balance, result._1(), count);
        final int byteLength = result._2.getLastResponse().map(s -> s.getBytes().length).orElse(0);
        responseCounts.putIfAbsent(byteLength, 0);
        responseCounts.put(byteLength, responseCounts.get(byteLength) + 1);
    }
    return responseCounts;
}

Map<Integer, Integer> getResponsesWithPayouts(int baseCostMultiplier, int reels, int visibleSymbols, String stakeCostUuid, int totalBets) throws InsufficientFundsException{
    final int stake = getStake(baseCostMultiplier, stakeCostUuid);
    long balance = 10L * stake;
    final TestGpasPlatform testGpasPlatform = TestGpasPlatform.create(ryotaAdapter, TestGpasPlatform.DEFAULT_MIN_BET, Math.max(stake, TestGpasPlatform.DEFAULT_MAX_BET), TestGpasPlatform.DEFAULT_MAX_WIN, ImmutableList.of(baseCostMultiplier));
    final Map<Integer, Integer> responseCounts = new HashMap<>();
    for (int count = 0; count < totalBets; count++) {
        final Tuple2<List<Output>, TestGpasPlatform> result = playWithRealRng(baseCostMultiplier, count, reels, visibleSymbols, stakeCostUuid, testGpasPlatform);

        // If we run out of balance, re-start, we want to do meaningful spins that trigger features, etc
        balance = checkBalance(stake, balance, result._1(), count);

        final int byteLength = result._2.getLastResponse().map(s -> s.getBytes().length).orElse(0);
        final PlayData playData = result._2.getLastResponse().map(s -> new Gson().fromJson(s, GdkPlayData.class)).orElse(new GdkPlayData());
        final java.util.List<SlotsActionData> actionData = playData.findLastPlay().getLastPlayInModeData().getSlotsData().getActions();
        final int sumOfPayouts = actionData.stream()
                                           .map(SlotsActionData::getPayouts)
                                           .mapToInt(java.util.List::size)
                                           .sum();
        responseCounts.putIfAbsent(byteLength, sumOfPayouts);
    }
    return responseCounts;
}

The first 6 lines of code of each of these methods are totally duplicated, but I'm not sure how I should or can clean this up.
I think an extension of this problem is that I have two chains of method calls which do the same thing for all but the data that is collected, and instead of having a boolean operator to split this functionality as I thought that was bad design, I implemented a new chain of methods to get it done. Should I have done this differently?

A: You can create one common method and pass type like withCount as below,
Map<Integer, Integer> getResponses(int baseCostMultiplier, int reels, int visibleSymbols, String stakeCostUuid, int totalBets, boolean withCount) throws InsufficientFundsException {
    final int stake = getStake(baseCostMultiplier, stakeCostUuid);
    long balance = 10L * stake;
    final TestGpasPlatform testGpasPlatform = TestGpasPlatform.create(ryotaAdapter, TestGpasPlatform.DEFAULT_MIN_BET, Math.max(stake, TestGpasPlatform.DEFAULT_MAX_BET), TestGpasPlatform.DEFAULT_MAX_WIN, ImmutableList.of(baseCostMultiplier));

    final Map<Integer, Integer> responseCounts = new HashMap<>();
    for (int count = 0; count < totalBets; count++) {
        final Tuple2<List<Output>, TestGpasPlatform> result = playWithRealRng(baseCostMultiplier, count, reels, visibleSymbols, stakeCostUuid, testGpasPlatform);
        // If we run out of balance, re-start, we want to do meaningful spins that trigger features, etc
        balance = checkBalance(stake, balance, result._1(), count);
        final int byteLength = result._2.getLastResponse().map(s -> s.getBytes().length).orElse(0);

        if(withCount) {
            responseCounts.putIfAbsent(byteLength, 0);
            responseCounts.put(byteLength, responseCounts.get(byteLength) + 1);
        }else{
            final PlayData playData = result._2.getLastResponse().map(s -> new Gson().fromJson(s, GdkPlayData.class)).orElse(new GdkPlayData());
            final java.util.List<SlotsActionData> actionData = playData.findLastPlay().getLastPlayInModeData().getSlotsData().getActions();
            final int sumOfPayouts = actionData.stream()
                    .map(SlotsActionData::getPayouts)
                    .mapToInt(java.util.List::size)
                    .sum();
            responseCounts.putIfAbsent(byteLength, sumOfPayouts);
        }
    }
    return responseCounts;
}


text:
Q: Find routes between 2 points in R With following data of start and end points, how can we get routes between 2 points.
> ddf
  start end
1     a   b
2     a   c
3     b   e
4     b   f
5     b   c
6     a   d
7     e   f
8     f   g

> dput(ddf)
structure(list(start = structure(c(1L, 1L, 2L, 2L, 2L, 1L, 3L,
4L), .Label = c("a", "b", "e", "f"), class = "factor"), end = structure(c(1L,
2L, 4L, 5L, 2L, 3L, 5L, 6L), .Label = c("b", "c", "d", "e", "f",
"g"), class = "factor")), .Names = c("start", "end"), class = "data.frame", row.names = c(NA,
-8L))
>

This page (http://www.anselm.edu/homepage/mmalita/culpro/graf1.html) shows only 2 line solution in Prolog! Following code works but does not give correct output list. It can be started with mainpath(ddf, 'a', 'f') to find path between 'a' and 'f'.
mainpath = function(ddf, startpt, endpt){
    ddf$start = as.character(ddf$start)
    ddf$end = as.character(ddf$end)
    nodenames = sort(unique(c(ddf$start, ddf$end)))
    routev=c(startpt)
    if(is_arc(ddf, startpt, endpt, routev)) {return("Direct route found."); }
    else{
        nodenames = nodenames[which(nodenames!=startpt)]
        nodenames = nodenames[which(nodenames!=endpt  )]
        if(is_path(ddf, nodenames, startpt, endpt, routev))
            return ("Completed successfully")
        else return ("Could not find a path.")
    }
}

is_arc = function(ddf, frompt, topt, routevector){
    len = nrow(ddf)
    for(i in 1:len)
        if(frompt == ddf$start[i] && topt == ddf$end[i]) {
            routevector = append(routevector, frompt)
            routevector = append(routevector, topt)
            print(routevector)
            return (TRUE);
        }
    return (FALSE)
}

is_path = function(ddf, othernodes, frompt, topt, routevector){

    if(is_arc(ddf, frompt, topt, routevector)){
        return (TRUE)
    }
    if(length(othernodes)==0){
        print(routevector)
        return (FALSE)
    }
    for(i in 1:length(othernodes)){
        intermediate = othernodes[i]
        if(is_arc(ddf, frompt, intermediate, routevector) && is_path(ddf, othernodes, intermediate, topt, routevector)){
            return (TRUE)
        }
    }
    print(routevector)
    return (FALSE)
}

I am sure it can be much improved, especially all these for loops etc can be removed using apply etc functions. I know that packages with such functions are available but how can it be done in base R?
Your answers / comments will be appreciated.

A: While I'm sure there are wonderful ways to do this with linear algebra, here's a relatively intuitive method (using dplyr here, but translate as you like):
library(dplyr)

# convert factors to characters, filter down to possible starting points
df %>% mutate_each(funs(as.character)) %>% filter(start == 'a') %>%
    # join to add possible next steps, indexing endpoints to startpoints
    left_join(df, by = c('end' = 'start')) %>%
    # iterate for successive steps
    left_join(df, by = c('end.y' = 'start')) %>%
    left_join(df, by = c('end.y.y' = 'start')) %>%
    # chop out rows that didn't end at 'g' (omit if you're curious)
    filter(apply(., 1, function(x){x[length(na.omit(x))]}) == 'g')

#   start end.x end.y end.y.y  end
# 1     a     b     e       f    g
# 2     a     b     f       g <NA>

If df is factors, you'll get warnings about coercing, though it'll run fine (coerce to start or add %>% mutate_each(funs(as.character)) to each df call and they'll go away). The column names are a bit ugly; set them with left_join's suffix parameter or select or rename if you like.
Obviously the iteration of joins invites a loop, which might look as such:
df2 <- df %>% mutate_each(funs(as.character)) %>% filter(start == 'a')

for(i in 0:2){
  endcol <- paste0('end', paste(rep('.y', i), collapse = ''))
  df2 <- df2 %>% left_join(df, by = setNames('start', endcol))
}

df2 %>% filter(apply(., 1, function(x){x[length(na.omit(x))]}) == 'g')

#   start end.x end.y end.y.y  end
# 1     a     b     e       f    g
# 2     a     b     f       g <NA>

If you set the number of iterations too high, it will error out because there are no rows to join to, but the error is actually quite convenient, as the loop has already saved the df2 you want, so the error just stops extra work from being done. Add tryCatch if you like, or go the other direction and refactor it into a scary-looking while loop which will actually iterate the perfect number of times:
df2 <- df %>% mutate_each(funs(as.character)) %>% filter(start == 'a')
endcol <- 'end'    # initialize iterating variable

while(TRUE){
  df2 <- df2 %>% left_join(df, by = setNames('start', endcol))
  endcol <- paste0(endcol, '.y')
}

df2 %>% filter(apply(., 1, function(x){x[length(na.omit(x))]}) == 'g')

#   start end.x end.y end.y.y  end
# 1     a     b     e       f    g
# 2     a     b     f       g <NA>

A: Following is much shorter and easily understandable, recursive function using base R. (First 2 lines are not needed if start and end columns of data.frame being sent are already character and not factor).
mainpath2 = function(ddf, startpt, endpt, route=c()){
    ddf$start = as.character(ddf$start)
    ddf$end = as.character(ddf$end)
    if(startpt == endpt) return("Error: Same Start and End points.\n")
    for(i in 1:nrow(ddf)){
        if(ddf$start[i] == startpt){
            route = append(route, startpt)
            if(ddf$end[i] == endpt){
                # PATH FOUND:
                route = append(route, endpt)
                print(route)
            }
            else mainpath2(ddf[-i, ], ddf$end[i], endpt, route)
            route = route[-length(route)]
        }
    }
}

> mainpath2(ddf, 'a', 'g')
[1] "a" "b" "e" "f" "g"
[1] "a" "b" "f" "g"


text:
Q: Finding updates in a table using Self-Join I have a table as shown below
tablename - property
|runId|listingId|listingName
   1    123       abc
   1    234       def
   2    123       abcd
   2    567       ghi
   2    234       defg

As you can see in above code there is a runId and there is a listing Id. I am trying to fetch for a particular runId which are the new listings added (In this case for runId 2 its 4th row with listing id 567 ) and which are the listing Ids that are update (In this case its row 3 and row 5 with listingId 123 and 234 respectively)
I am trying self join and it is working fairly for new updates but new additions are giving me trouble
SELECT p1.* FROM property p1
    INNER JOIN  property p2
        ON p1.listingid = p2.listingid
            WHERE p1.runid=456 AND p2.runid!=456

The above query provides me correct updated records in the table. But I am not able to find new listing. I used p1.listingid != p2.listingId , left outer join, still wont work.

A: You may try this.
with cte as (
select row_number() over (partition by listingId order by runId) as Slno, * from property
)
select * from property where listingId not in (
select  listingId from cte as c where slno>1
)    --- for new listing added

with cte as (
select row_number() over (partition by listingId order by runId) as Slno, * from property
)
select * from property where listingId in (
select  listingId from cte as c where slno>1
)   --- for modified listing

A: I would use the ROW_NUMBER() analytical function for it.
SELECT
    T.*
FROM
    (
        SELECT
            T.*,
            CASE
                WHEN ROW_NUMBER() OVER(
                    PARTITION BY LISTINGID
                    ORDER BY
                        RUNID
                ) = 1 THEN 'INSERTED'
                ELSE 'UPDATED'
            END AS OPERATION_
        FROM
            PROPERTY
    )
WHERE
    RUNID = 2
    -- AND OPERATION_ = 'INSERTED'
    -- AND OPERATION_ = 'UPDATED'

This will provide the result as updated if listingid is added in any of the previous runid
Cheers!!

A: For this, I would recommend exists and not exists.  For updates:
select p.*
from property p
where exists (select 1
              from property p2
              where p2.listingid = p.listingid and
                    p2.runid < p.runid
             );

If you want the result for a particular runid, add and runid = ? to the outer query.
And for new listings:
select p.*
from property p
where not exists (select 1
                  from property p2
                  where p2.listingid = p.listingid and
                        p2.runid < p.runid
                 );

With an index on property(listingid, runid), I would expect this to have somewhat better performance than a solution using window functions.
Here is a db<>fiddle.


text:
Q: How to avoid "E2251 Ambiguous overloaded call to 'MyMethodName'" when using open array parameters? Sometimes I get "E2251 Ambiguous overloaded call to 'MyMethodName'" when passing open arrays to overloaded methods.
Example:
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    procedure Test(AArrA : array of integer); overload;
    procedure Test(AArrA : array of TObject); overload;
  end;

...

procedure TForm1.FormCreate(Sender: TObject);
begin
  Test([10, 15]);
end;

It produces the following error:

[DCC Error] Unit1.pas(37): E2251 Ambiguous overloaded call to 'Test'

Until now, I've always used a temporary dynamic array due to avoid the error but I don't find it very clean
procedure TForm1.FormCreate(Sender: TObject);
var
  Tmp : array of integer;
begin
  SetLength(Tmp, 2);
  Tmp[0] := 10;
  Tmp[1] := 15;

  Test(Tmp);
end;

Is there a cleaner way to help Delphi discerning between overloads which accepts open array parameters?


text:
Q: Error when using Pandas pivot_table with margins=True My code (from the book Python Data Science Handbook (O'Reilly)):
Full disclosure: at the time of writing, the book is still in early release, meaning that it's still unedited and in its raw form.
import numpy as np
import pandas as pd
import seaborn as sns
titanic = sns.load_dataset('titanic')

titanic.pivot_table('survived', index='sex', columns='class')

The result is:

However, if I now try to add totals using the margins keyword, the following error occurs:
titanic.pivot_table('survived', index='sex', columns='class', margins=True)

TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category

Any idea what could be causing this?
Version info:

*

*Python 3.4.2

*pandas 0.16.2

*numpy 1.9.2

A: This appears to be due to a change between pandas 0.15 and 0.16. In previous versions, the titanic dataset has this dtype:
In [1]: import pandas, seaborn

In [2]: pandas.__version__
'0.15.2'

In [3]: titanic = seaborn.load_dataset('titanic')

In [4]: titanic.dtypes
Out[4]:
survived         int64
pclass           int64
sex             object
age            float64
sibsp            int64
parch            int64
fare           float64
embarked        object
class           object
who             object
adult_male        bool
deck            object
embark_town     object
alive           object
alone             bool
dtype: object

With the newer pandas:
In [1]: import pandas, seaborn

In [2]: pandas.__version__
'0.16.2'

In [3]: titanic = seaborn.load_dataset('titanic')

In [4]: titanic.dtypes
Out[4]:
survived          int64
pclass            int64
sex              object
age             float64
sibsp             int64
parch             int64
fare            float64
embarked         object
class          category
who              object
adult_male         bool
deck           category
embark_town      object
alive            object
alone              bool
dtype: object

Several columns are automatically converted to categorical, which brings up this bug. The book is currently unpublished and unedited; I'll be sure to test with recent releases and fix these types of errors before publication.
For now, here is a workaround:
In [5]: titanic['class'] = titanic['class'].astype(object)

In [6]: titanic.pivot_table('survived', index='sex', columns='class', margins=True)
Out[6]:
class      First    Second     Third       All
sex
female  0.968085  0.921053  0.500000  0.742038
male    0.368852  0.157407  0.135447  0.188908
All     0.629630  0.472826  0.242363  0.383838

Edit: I submitted this as an issue to the pandas project: https://github.com/pydata/pandas/issues/10989


text:
Q: Error object object y salida de bucle en letras en vez de palabras con ajax Mi problema es que no se hacer una petición ajax en condiciones y por más que he visto por internet no me sale, me coge la información bien, el problema es que al recorrerla me salen letras como muestro en la siguiente captura y si pongo datatype:json me sale el error de object object, lo que quiero es enviar y recibir. Si alguien puede dar luz a esta cuestión se lo agradecería.

Archivo 1: este archivo JS envía una variable bandera booleana al archivo 2 php:
$(document).ready(function () {
// Le pasamos una variable bandera de estado
var flagAnonimo = "true";
$.ajax({
    url: './php/Funciones.php',
    type: 'POST',
    async: true,
    // Le pasamos la variable bandera
    data: { flagAnonimo:flagAnonimo },
    success: function (data) {

        console.log(data.id);
        var array = [];
        // Parsemos los datos para que se puedan utilizar
        var datos = JSON.stringify(data);
        var  array_resultado = JSON.parse(datos);

        console.log(array_resultado);

        for (var i in array_resultado){
            console.log(array_resultado[i]);
        }
        console.log("La variable bandera ha sido enviada y la variable unica creada."
        );

        }, error: function (data) {
        console.log('Se ha producido un error.' + data);
    }
});
});

Archivo 2: Este archivo recoge la variable bandera y la mete en un método para que en la clase (archivo 3 php) haga la consulta y me la devuelva:
require('./clases/Persona.php');

if (isset($_POST["flagAnonimo"])) {

$flag = $_POST["flagAnonimo"];

//Le pasamos la id a la clase persona y clave unica la metemos en la variable id_unica
$persona_creada_obj = new Persona($flag);

//Llamamos al método que genera una clave unica
$persona_creada_obj->generar_id_unica($flag);

//Le pasamos el array a Funciones.js
echo json_encode($persona_creada_obj);

}

else {
    echo "esto no avanza :'(";
}

Archivo 3: esta es la clase como tal y aquí se hace la consulta y se devuelve en un array:
 class Persona {
    private $flag;
    private $arrayIdEstado;

    public function __construct($flag) {
        $this->flag = $flag;
    }

    public function generar_id_unica($flag){
        //Recibimos la variable bandera de Funciones.js
        if ($flag) {
            //Generamos una id unica
            $clave = uniqid();
            //Le quitamos los 4 primeros digitos porque daría un total de 13 digitos y en la base de datos tenemos 9
            //Le decimos que lo que genere va a ser la clave unica y que la retorne
            $id = substr($clave, 0, -4);

            include('Conexion.php');

            // Como al quitarle digitos a la clave única ya no es tan única consultamos a la base de datos si está
            $consulta = "SELECT id_unica_rol FROM rol WHERE id_unica_rol = '$id'";

            // Hacemos la conexión a la base de datos
            $resultado = mysqli_query($conexion, $consulta);

            // Entra si la clave ya existe
            if ($resultado == $id) {
                //Generamos una nueva id unica
                $clave_unica = uniqid();
                $id_unica = substr($clave_unica,0 -4);
                // Se la mandamos a la función de la misma clase con self
                self::insertarRol($id_unica);
            } else {
                self::insertarRol($id);
            }

            //Antes de salir cambiamos el estado de la flag porque si refrescamos la página vamos a tener la misma id y dará error
            $flagFalse = false;

            $arrayIdEstado = array("id" => $id, "flag" => $flagFalse);

            print_r($arrayIdEstado);

            return $arrayIdEstado;

        } else {
            echo "La variable bandera es false";
        }

    }

    // Así protegemos la inserción
    public function insertarRol($id) {
        include('Conexion.php');
        // INSERTAMOS DATOS TANTO EN LA TABLA ROL COMO USUARIO
        //Insertamos los datos primero en la de rol
        $insercion1 = "INSERT INTO rol(nombre,id_unica_rol) VALUES ('anonimo','$id')";

        //La insertamos conectandonos a la base de datos
        mysqli_query($conexion,$insercion1);

        //Cerramos la conexión con MYSQL
        mysqli_close($conexion);
    }

}

A: En esta parte del código la función generar_id_unica devuelve un array que no recoger en ninguna variable
$persona_creada_obj->generar_id_unica($flag);

//Le pasamos el array a Funciones.js
echo json_encode($persona_creada_obj);

Deberías recoger el resultado en una auxiliar que después envías al json_encode
$aux=$persona_creada_obj->generar_id_unica($flag);

//Le pasamos el array a Funciones.js
echo json_encode($aux);

Por otra parte tienes un print_f que debes eliminar en el archivo3
print_r($arrayIdEstado);

Esto provoca que la salida salga un var_dump q malforma el json


text:
Q: remove duplicated items with comparing list to another list There are a list1, list2 and list 3.

list 1 contains <british> <electric> <kettle> <and> <bottle> <of> <water>
list 2 contains <british> <electric> <bottle> <water>
the result of list 3 will be <kettle> <and> <of>

As you see, duplicated items     has been removed.
Anyone have a code with this?

A: You can use LINQ:
Dim in1Not2 = list1.Except(list2)
Dim list3 = in1Not2.ToList()

If your list2 also can contain items that are not in list1:
Dim uniqueIn1Or2 = list1.Except(list2).Concat(list2.Except(list1))
Dim list3 = uniqueIn1Or2.ToList()


text:
Q: LT3680 switcher output doesn't have regulation under no load I have a switcher circuit based on LT3680. I implemented the typical circuit shown in the datasheet in a well laid out 4-layer PCB. However, I find that the input voltage is present at the output at no load condition. When I add load of 100ohms and below, I get 5.05 constant output. The typical circuit is meant for 5V, 3.5A load. My loads draw only a few milli amps. So could that be because if the inductor saturating or something. The switcher has feedback and as far as I understand should be able to regulate the output whatsoever. Regulation kicks in only when I add 100 ohm or below. Nothing with 10K, haven't tried with anything in between since I don't have a wide range of resistors available with me. Please have a look at the circuit used.
Datasheet can be found at:
http://cds.linear.com/docs/en/datasheet/3680fb.pdf

A: The problem is very likely to be loop compensation.
This is a current mode architecture, so the output pole changes with load, but the output zero does not.
The output pole is at \$\frac {1} {2 \pi\ R_o C_o}\$; rearranging as \$R_o = \frac {V_o} {I_o}\$ we get:
\$f_p = \frac {I_o}  {2 \pi V_o C_o}\$
At very low load currents, the output pole is at a very low frequency and when added to the dominant pole at the \$V_c\$ pin, the arrangement could easily be unstable.
Positive feedback could indeed make Vo = Vi.
To cure this, you could add a capacitor (need to calculate it) from \$V_c\$ to ground and add a small (100pF perhaps) capacitor across R46
Another point to note is that for low load currents, the size of the inductor is very small (as load current increases the required inductance value decreases).
The inductor in the application circuit has been chosen for about 1A of ripple current; if you have only a few mA of load, then I calculate the inductor should be of the order 120μH assuming a maximum load of 100mA (for a ripple current of 40mA).
The datasheet gives guidance on this
\$ L = \left (\frac {V_O + V_D} {F_{sw} \cdot \Delta I_L} \right) \cdot \left ( 1 - \frac {V_O + V_D} {V_{in(max)}} \right)\$
See page 10 of the datasheet.


text:
Q: Where should I upload my app's files while using AWS? Recently I came into a situation while deploying my app to heroku, I learned that heroku has an ephemeral storage, meaning that after every update to my api, all my uploads would be deleted.
So I investigated a little bit more of how I could keep my files and I finally got an answer: Use AWS S3 Storage.
Given that I had to use AWS and I didn't want to create an account (for laziness), I decided to just create one and instead of heroku  and use and EC2 instance.
But now that I have configured my nginx, reverse proxy, ssl, etc, a question came to my mind. Should I use AWS S3 storage? Or Should I use the available space in the EC2 instance and just increase it when I need it?
My configuration is as follows:
I have an API built using node.js and express, the app runs using pm2 and I configured a reverse proxy, so every time a user goes to a subdomain pointing to the ec2 instance, the reverse proxy listens in both port 80 and 443 and redirect the traffic to 127.0.0.1:5000
Now, the thing is that the user has to upload profile picture and some other files, and they are uploaded at the same level of my project.
-- Project Folder
   -- routes
   -- model
   -- upload // I have subfolders here, and uploads are uploaded here.
   -- index.js

So, should I leave my project as it is or should I change the way that my uploads work?

A: You can use S3 as storage for your uploaded files. But you would have to update your code to be able to use the S3 SDK for uploading files to S3 storage. There is nothing wrong in storing images in EC2 as well as long as you do not run into millions of them. So your current setup is fine.


text:
Q: Why do I get TargetInvocationException in my threaded C# application? Here is the code (in a simple form):
delegate DataTable Functie();
Functie deleg;

DataTable find1()
{
    return new DataTable();
}
DataTable find2()
{
    return new DataTable();
}

private void btnFind1_Click(object sender, EventArgs e)
{
    deleg = this.find2;
    backgroundWorker1.RunWorkerAsync();
}

private void btnFind2_Click(object sender, EventArgs e)
{
    deleg = this.find1;
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker bk = sender as BackgroundWorker;
    e.Result = deleg;

    if (bk.CancellationPending)
    {
        e.Cancel = true;
    }
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        MessageBox.Show("Operation was canceled");
    }
    else if (e.Error != null)
    {
        MessageBox.Show("An error occurred: " + e.Error.Message);
    }
    else
    {
        dataGridView1.DataSource = (DataTable)e.Result;
    }
}

So, basically I have 2 functions find1 and find2 and these are long-time-processing functions. I want to run these 2 functions on an BackgroundThread so I created a delegate. When i call one function, the delegate takes the address of a function or the other.
When I start the thread, I pass the delegate instead of directly typing the function, so I won't create 2 background threads, each with its own events and stuff.
But I run into problems, when I run the program, the following error is thrown:
"System.Reflection.TargetInvocationException was unhandled
Exception has been thrown by the target of an invocation."

It has to do with the delegate passed to the thread. I can, of course, write everything simpler with conditions to see what functions has to be ran, but I got into this and I didn't know how to solve it. I want to know what I did wrong.

A: I think, in your DoWork function, you need to call the delegate like this:
e.Result = deleg();

The reason is that this will actually invoke the function, rather than just set the result equal to a reference to the function.

A: You're casting a delegate to a DataTable:
dataGridView1.DataSource = (DataTable)e.Result;

which came from here:
e.Result = deleg;

Did you mean:
e.Result = deleg();


text:
Q: How do I use multiple list()/each() calls in a while loop? I'm working with 3 different arrays (although I'm only testing with two for the time being) and I'm trying to process the arrays on $_POST.  I'm currently using:
while(list($key_member,$member)=each($_POST['member_ids'])
    && list($key_amount,$amount)=each($_POST['payment_amounts']))
{
    echo "MEMBER: $member
";
    echo "AMOUNT: $amount

";
}

If I use one list() on either array it will print the info for that particular item.  However, if I attempt to use multiple list() commands in the while, only the last  list()ed item gets filled properly.  Is list() doing some trickery in the background that's preventing it from working in a while loop?
Obviously the "easy" solution would be to use an index and simply force the issue, but I prefer enumerating -- and I'm honestly just curious as to
What am I doing wrong, and/or what is "broken" with list()?

A: bug? dunno.
here's a workaround.
while(list($key_member,$member)=each($_POST['member_ids'])){
   list($key_amount,$amount)=each($_POST['payment_amounts']);
   echo "MEMBER: $member
";
   echo "AMOUNT: $amount

";
}

A: You could extract each array's keys using array_keys(), which produces an indexed array, then keep separate loop counters for each array:
$member_ids = array_keys($_POST['member_ids']);
$amounts = array_keys($_POST['payment_amounts']);

$mi = 0;
$am = 0;
while(1) {
   ...

   $mi++
   $am++;
   if (count($member_ids) >= $mi) && (count(amounts) >= $am) {
      break;
   }
}

A: && is evaluated in a short-circuit manner, the first statement to return false jumps out of it. In your case it stops to iterate as soon as the first array is at its end. list should work fine here, as it's a language construct which assigns variables.


text:
Q: New Google API Key "Google Maps API v3" doesn't work for Google Places API? I am working with the Google Places API (https://developers.google.com/places/documentation/search), and have generated a new Google API Key with 'Any IP Allowed'. When I try to get the results of the API service URLs below, I am getting a REQUEST DENIED error.
https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&sensor=false&key=AIzaSyA3vtFM8AMlIO853ra82KzryBs752VIWts
https://maps.googleapis.com/maps/api/place/search/xml?key=AIzaSyA3vtFM8AMlIO853ra82KzryBs752VIWts&location=-33.8670522,151.1957362&radius=1000&sensor=false
I have tried all combinations of the request parameters, but nothing has worked.

A: You must also activate the places-service in the API-console.

A: Please follow the Authentication instructions on the Places API Documentation getting started page to activate the Places API Web Service for your APIs Console Key.


text:
Q: Adding dependency to kotlin-multiplatform libs published with gradle metadata I am trying to add a gradle dependency in my kotlin-multiplatform lib. The dependency is com.soywiz.korlibs.klock:klock:1.9.1:. If I use gradle 4.10.1 the one I was using previously, It works like a charm. But I want to use gradle 6 so that I can use it with the kotlin-multiplatform plugin 1.3.70
It fails with the error bellow:-
> Could not resolve all dependencies for configuration ':jsNpm'.
   > Could not resolve com.soywiz.korlibs.klock:klock-metadata:1.9.1.
     Required by:
         project :
      > Unable to find a matching variant of com.soywiz.korlibs.klock:klock-metadata:1.9.1:
          - Variant 'metadata-api' capability com.soywiz.korlibs.klock:klock-metadata:1.9.1:
              - Incompatible attributes:
                  - Required org.gradle.usage 'kotlin-runtime' and found incompatible value 'kotlin-api'.
                  - Required org.jetbrains.kotlin.platform.type 'js' and found incompatible value 'common'.
              - Other attribute:
                  - Found org.gradle.status 'release' but wasn't required.

What do I do to get this error resolved?


text:
Q: Generate Random Number I'm trying to generate random numbers depending on the user Input. So if the user inputs 10 then I want to generate 10 random numbers.I'm getting the user input from a textbox.
   private void GenerateRandomNumber()
            {

                int count = 1;

                //Int32.TryParse(GeneratetextBox.Text, out UserNumber);
                UserNumber = Convert.ToInt32(GeneratetextBox.Text);

                ///creates random object to produce random values
                Random randomNumbers = new Random();

                while (count == UserNumber)
                {
                    //UserNumber = randomNumbers.Next(100);

                    listBox.Items.Add(randomNumbers.Next(100));

                    count = count + 1;
                }

                //for ( count = UserNumber; count == UserNumber; count++)
                //{
                //    UserNumber = randomNumbers.Next(100);

                //    listBox.Items.Add(randomNumbers.Next(100));

                //    count = count + 1;
                //}
    }

A: Try this to genearate random numbers:
        private void GenerateRandomNumber()
        {
            int userNumber= Convert.ToInt32(GeneratetextBox.Text);

            Random randomNumbers = new Random();

             // loop until i is not les than userNumber

            for (int i = 0; i < userNumber; i++){
                  // generate random number and add it to the list.
                  int randNumber= randomNumbers.Next(100);
                  listBox.Items.Add(randNumber);
            }
          }

          private void button1_Click(object sender, EventArgs e)
          {
             // clear listbox before generating new numbers
             listBox.Items.Clear();
             GenerateRandomNumber();
           }

If your are triggering this method with a button don't forget to clear your listbox before generating new randnubers.

A: Your while loops stops when count is different from UserNumber, so since you initialize count = 1 you need to have UserNumber = 1 if you want the code in the while to be executed.
So, you need to fix the while condition:
private void GenerateRandomNumber()
            {
            int count = 1;

            //Int32.TryParse(GeneratetextBox.Text, out UserNumber);
            UserNumber = Convert.ToInt32(GeneratetextBox.Text);

            ///creates random object to produce random values
            Random randomNumbers = new Random();

            while (count <= UserNumber)
            {
                //UserNumber = randomNumbers.Next(100);

                listBox.Items.Add(randomNumbers.Next(100));

                count = count + 1;
            }

            //for ( count = UserNumber; count == UserNumber; count++)
            //{
            //    UserNumber = randomNumbers.Next(100);

            //    listBox.Items.Add(randomNumbers.Next(100));

            //    count = count + 1;
            //}
}

That way the code inside the while will stop being executed when UserNumber is greater than count, which is what you are looking for.


text:
Q: Value does not fall within the expected range - CSOM What is the reason for the below exception message in CSOM code which I received when querying for data from SharePoint Online?
Value does not fall within the expected range.
Code sample:
public static void siteCountHelper(String siteUrl, CredentialSharePoint c, List<SiteCountHelper> results)
     {
         try
         {
             ClientContext client = new ClientContext(siteUrl);
             client = sharepointOnline(client, c);//setting credential
             var web = client.Web;
             client.Load(web, w => w.Webs, w => w.ServerRelativeUrl);
             var lists = client.LoadQuery(client.Web.Lists.Where(temp => temp.BaseType != BaseType.DocumentLibrary));
             var documentLibraries = client.LoadQuery(client.Web.Lists.Where(temp => temp.BaseType == BaseType.DocumentLibrary));
             client.ExecuteQuery();
             SiteCountHelper helper = new SiteCountHelper
             {
                 websCount = web.Webs.Count,
                 listsCount = lists.Count(),
                 documentLibrariesCount = documentLibraries.Count()
             };
             results.Add(helper);
             if (web.Webs.Count != 0)
             {
                 String tempUrl = siteUrl.Replace(web.ServerRelativeUrl, "");
                 foreach (var w in web.Webs)
                 {
                     String mainUrl = tempUrl + w.ServerRelativeUrl;
                     siteCountHelper(mainUrl, c, results); //recursive call
                 }
             }
         }
         catch (Exception e)
         {
             log(e.Message);
         }
     }


text:
Q: Parse JSON array response to FlatList in React Native I'm willing to parse the above JSON response to a FlatList, but I can't figure what I'm missing. Since it does not have a key and value pair, I'm not sure how to render it.

{"list":["a","b","c","d"]}

My code is...

import React from 'react';
import { View, FlatList, Text } from 'react-native';

export default class Home extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = { dataSource: [] };
  }

  async componentDidMount() {
    const response = await fetch('http://.../');
    const responseJson = await response.json();
    this.setState({ dataSource: responseJson.list });
  }

  render() {
    return (
      <View style={{ flex: 1, paddingTop: 20 }}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({ item, index }) => <Text>{item[index]}</Text>}
          keyExtractor={(item, index) => index}
        />
      </View>
    );
  }
}

A: Your problem is because you're doing the below
renderItem={({ item, index }) => <Text>{item[index]]}</Text>}

item is referring to a,b,c,d but you're doing a[index],b[index] which clearly wrong
Solutions:
<FlatList
...
  renderItem={({ item }) => <Text>{item}</Text>}
...
/>

You don't need index for your renderItem because the item is already a,b,c,d respectively

A: You dont need item index, try the below code and let me know.

import React from 'react';
import { View, FlatList, Text } from 'react-native';

export default class Home extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = { dataSource: [] };
  }

  async componentDidMount() {
    const response = await fetch('http://.../');
    const responseJson = await response.json();
    this.setState({ dataSource: responseJson.list });
  }

  render() {
    return (
      <View style={{ flex: 1, paddingTop: 20 }}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item}</Text>}
          keyExtractor={this.state.dataSource.indexOf(item)}
        />
      </View>
    );
  }
}


text:
Q: query with date range condition returns empty result I have a query that reads some records from a table that are in a specific date range. I am using PHP under codeigniter framework and the query is pretty simple.
$this->db->select('aa.code,aa.employee_code ,aa.assign_date,aa.asset_serial_no');
$this->db->from('asset_assigns as aa');
$this->db->where("aa.assign_date >= $date1");

The above works fine!
$this->db->select('aa.code,aa.employee_code ,aa.assign_date,aa.asset_serial_no');
$this->db->from('asset_assigns as aa');
$this->db->where("aa.assign_date <= $date2");

The above also reads proper number of queries!
$this->db->select('aa.code,aa.employee_code ,aa.assign_date,aa.asset_serial_no');
$this->db->from('asset_assigns as aa');
$this->db->where("aa.assign_date <= $date2");
$this->db->where("aa.assign_date >= $date1");

But this one with two 'where' returns empty!!!

A: $this->db->where("aa.assign_date <= $date2 AND aa.assign_date >= $date1");

A: for date comparisions use mysql datediff and timediff functions.
$this->db->where("datediff(aa.assign_date,$date2) <= 0 and datediff(aa.assign_date,$date1) >= 0");

If you are not explicit, dates are compared as strings.  consider the two queries:
select date('2010/10/01') > date('2010/2/15');

with a date comparison you get the correct output of '1', first date is greater than second date, whereas:
select '2010/10/01' > '2010/2/15';

with a string comparison, you get '0' which is the wrong output for dates (but the right output for strings).

A: I am not sure how are these db methods are implemented in codeignitor
but probably you can replace;
$this->db->where("aa.assign_date <= $date2");
$this->db->where("aa.assign_date >= $date1");

with
$this->db->where("aa.assign_date <= $date2 AND aa.assign_date >= $date1");


text:
Q: Rename a redshift SQL table within PySpark Databricks I want to rename a redshift table within a Python Databricks notebook.
Currently I have a query that pulls in data and creates a table:
redshiftUrl = 'jdbc:redshift://myredshifturl'

redshiftOptions = {
  'url':          redshiftUrl,
  'aws_iam_role': 'myredshift_iam_role',
  'tempdir':      's3bucket',
}

def run_query(query_string):
  # returns a df
  return spark.read.format('com.databricks.spark.redshift').options(**redshiftOptions).option('query', query_string)

query = """
SELECT TOP 100 * FROM public.mytable
"""

df = run_query(query).load()

def write_table(src_table, table_name=None, write_mode='overwrite', diststyle=None, distkey=None, sortkeyspec=None, preactions=None, postactions=None):
  srcDf = src_table
  loadOptions = redshiftOptions
  loadOptions['tempformat'] = 'CSV GZIP'
  loadOptions['extracopyoptions'] = 'truncatecolumns'
  if diststyle:
    loadOptions['diststyle'] = diststyle
  if distkey:
    loadOptions['diststyle'] = 'key'
    loadOptions['distkey'] = distkey
  if sortkeyspec:
    loadOptions['sortkeyspec'] = sortkeyspec
  if preactions:
    loadOptions['preactions'] = preactions
  if postactions:
    loadOptions['postactions'] = postactions
  if table_name == None: table_name = src_table
  srcDf.write.format('com.databricks.spark.redshift').options(**loadOptions).option('dbtable', table_name).mode(write_mode).save()

write_table(df, table_name = 'public.test')

I want to take this table I created and rename it. I referenced this doc but find it hard to follow.
I want to run this SQL command alter table public.test rename to test_table_to_be_dropped in my pyspark databricks notebook. (this command works within my SQL IDE)
Here's what I have tried:
test_query = """
alter table public.test rename to test_table_to_be_dropped
"""
run_query(test_query).load()

This gives me an error:
java.sql.SQLException: [Amazon](500310) Invalid operation: syntax error at or near "table"

It leads me to believe that my run_query() function is only for reading data and not for editing data. I also saw that I can use the %sql magic command, but it looks like it will only reference my data lake and not my redshift database.
TL;DR:
Is there a way I can write a function to use sql write commands or to point my %sql magic command to reference my redshift table?
I want to run this SQL command alter table public.test rename to test_table_to_be_dropped in my pyspark databricks notebook. (this command works within my SQL IDE)

A: AWS Redshift has a postactions and preactions parameter that allows you to write SQL queries after your write query.
def write_table(src_table, table_name=None, diststyle=None, distkey=None, sortkeyspec=None, preactions=None, postactions=None):
  srcDf = src_table
  loadOptions = redshiftOptions
  loadOptions['tempformat'] = 'CSV GZIP'
  loadOptions['extracopyoptions'] = 'truncatecolumns compupdate off'
  if diststyle:
    loadOptions['diststyle'] = diststyle
  if distkey:
    loadOptions['diststyle'] = 'key'
    loadOptions['distkey'] = distkey
  if sortkeyspec:
    loadOptions['sortkeyspec'] = sortkeyspec
  if preactions:
    loadOptions['preactions'] = preactions
  if postactions:
    loadOptions['postactions'] = postactions
  if table_name == None: table_name = src_table
  srcDf.write.format('com.databricks.spark.redshift').options(**loadOptions).option('dbtable', table_name).mode('overwrite').save()

sql_query = """
ALTER TABLE some sql actions;
DROP TABLE mytable
"""

write_table(df,table_name=mytable,postactions=sql_query)


text:
Q: Rename file in c#.net when its is uploaded through file upload control and save chang name of file in database I have file uploader through which i browse file
and strore the name of of browse file in string variable .
now i want rename this uplaod file name with another name which stored in another string variable
string strRoleValue = ddlrole.SelectedValue;

 string strfilename = FileUpload1.FileName;
 string existpath = Server.MapPath("~\\JD\\");
 DirectoryInfo ObjSearchFile = new DirectoryInfo(existpath);
  string saveLocation = existpath + strfilename;
FileUpload1.SaveAs(saveLocation);

strRoleValue  this variable contains the name with which i want use to rename a file uploaded through fileupload.
filename uploaded through fileupload control stored in strfilename.
so before saving this file in specified folder
 i want to rename it with strRoleValue  value.
how can i achieve this..plz help

A: You can check out the following link
http://asp-net-example.blogspot.in/2009/01/aspnet-fileupload-example-how-to-rename.html
<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>asp.net FileUpload example: how to rename file when upload (change file name when upload)</title>

    <form id="form1" runat="server">

asp.net FileUpload example: File Rename

        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="OrangeRed"
             >
        </asp:Label>

        <asp:FileUpload
             ID="FileUpload1"
             runat="server"
             BackColor="DeepPink"
             ForeColor="AliceBlue"
             />
        <asp:Button
             ID="Button1"
             runat="server"
             Font-Bold="true"
             ForeColor="DeepPink"
             OnClick="Button1_Click"
             Text="Upload It"
             />

    </form>

A: <input name="fileUploadedButtonName" type="file" />

public ActionResult Register(HttpPostedFileBase fileUploadedButtonName){

 string newFileName= "";

 if (fileUploadedButtonName != null)
   {
     string path = HttpContext.Server.MapPath(@"~/YourFolderName");

     bool exists = System.IO.Directory.Exists(path);

     if (!exists)
        System.IO.Directory.CreateDirectory(path);

     string extension = Path.GetExtension(fileUploadedButtonName.FileName);
     newFileName= Guid.NewGuid() + extension;
     string filePath = Path.Combine(path, newFileName);
     fileUploadedButtonName.SaveAs(filePath);

   }

}


text:
Q: Check if file contains string So I found this question on here, but I'm having an issue with the output and how to handle it with an if statement. This is what I have, but it's always saying that it's true even if the word monitor does not exist in the file
if File.readlines("testfile.txt").grep(/monitor/)
  do something
end

Should it be something like == "nil"? I'm quite new to ruby and not sure of what the outputs would be.

A: Grep will give you an array of all found 'monitor's. But you don't want an array, you want a boolean: is there any 'monitor' string in this file?
This one reads as little of the file as needed:
if File.open('test.txt').lines.any?{|line| line.include?('monitor')}
  p 'do something'
end

readlines reads the whole file, lines returns an enumerator which does it line by line.
update
#lines are deprecated, Use #each_line instead
  if File.open('test.txt').each_line.any?{|line| line.include?('monitor')}
    p 'do something'
  end

A: I would use:
if File.readlines("testfile.txt").grep(/monitor/).any?

or
if File.readlines("testfile.txt").any?{ |l| l['monitor'] }

Using readlines has scalability issues though as it reads the entire file into an array. Instead, using foreach will accomplish the same thing without the scalability problem:
if File.foreach("testfile.txt").grep(/monitor/).any?

or
if File.foreach("testfile.txt").any?{ |l| l['monitor'] }

See "Why is "slurping" a file not a good practice?" for more information about the scalability issues.

A: Enumerable#grep does not return a boolean; it returns an array (how would you have access to the matches without passing a block otherwise?).
If no matches are found it returns an empty array, and [] evaluates to true.  You'll need to check the size of the array in the if statement, i.e.:
if File.readlines("testfile.txt").grep(/monitor/).size > 0
  # do something
end

The documentation should be your first resource for questions like this.

A: if anyone is looking for a solution to display last line of a file where that string occurs just do
File.readlines('dir/testfile.txt').select{|l| l.match /monitor/}.last

example
file:
monitor 1
monitor 2
something else

you'll get
monitor 2

A: I generally skip ruby for the command-line utilities as they tend to be faster.
`grep "monitor" "testfile.txt" > /dev/null`
$?.success #=> true if zero exit status, false otherwise.


text:
Q: How to migrate Fusion Tables SQL API with New API in Java I am using Fusion Table SQL API in Java language and Application is hosted in Google App engine.
Application is adding and deleting record from fusion table by Java language.
But
The Fusion Tables SQL API has been officially deprecated as of June 26, 2012 and will be shut down on December 26, 2012.
So, I have to migrate Fusion Tables SQL API with New API.
My question is How to migrate Fusion Tables SQL API with New API in Java?
My current script is
import com.google.gdata.client.ClientLoginAccountType;
    import com.google.gdata.client.GoogleService;
    import com.google.gdata.client.Service.GDataRequest;
    import com.google.gdata.client.Service.GDataRequest.RequestType;

    import com.google.gdata.util.AuthenticationException;
    import com.google.gdata.util.ContentType;
    import com.google.gdata.util.ServiceException;

    import java.io.IOException;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.Scanner;
    import java.util.regex.MatchResult;
    import java.util.regex.Pattern;

    public class SampleProgram {

      private static final String SERVICE_URL = "https://www.google.com/fusiontables/api/query";

      private static final Pattern CSV_VALUE_PATTERN = Pattern.compile("([^,\\r\\n\"]*|\"(([^\"]*\"\")*[^\"]*)\")(,|\\r?\\n)");

      private GoogleService service;

      public SampleProgram(String email, String password) throws AuthenticationException
      {
        service = new GoogleService("fusiontables", "fusiontables.ApiExample");
        service.setUserCredentials(email, password, ClientLoginAccountType.GOOGLE);
      }

      public String GetrunSelectQuery(String selectQuery) throws IOException,ServiceException
      {
          URL url = new URL(SERVICE_URL + "?sql=" + URLEncoder.encode(selectQuery, "UTF-8"));
            GDataRequest request = service.getRequestFactory().getRequest(RequestType.QUERY, url, ContentType.TEXT_PLAIN);

            request.execute();
            String decoded="";
            Scanner scanner = new Scanner(request.getResponseStream(),"UTF-8");
            while (scanner.hasNextLine()) {
              scanner.findWithinHorizon(CSV_VALUE_PATTERN, 0);
              MatchResult match = scanner.match();

              String quotedString = match.group(2);
              decoded = quotedString == null ? match.group(1): quotedString.replaceAll("\"\"", "\"");

            }
            return decoded;
      }

      public static void main(String[] args) throws ServiceException, IOException
      {

        String tableEncryptedID="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        String sEmailId="XXXX@XXXXX.com";
        String sPassword="XXXXXXXXX";
        SampleProgram obj = new SampleProgram(sEmailId, sPassword);

        System.out.println(obj.GetrunSelectQuery("select name from "+tableEncryptedID+" limit 1"));

      }
    }


text:
Q: It is posible to embed the Unreal Engine 4/Unity3D into an iOS native app? I have to develop an iOS native app that renders a 3D model on the background with some iOS native UI over the render, and obviously it has to be a 2 ways communication between the 3D engine and the UI, for example to call an animation from the UI and know when the animation have finished.
I found this post that shows how to embed a Unity3D scene but it does not explain anything about the communication.
I would like to know if this is posible with Unity3D and UE4, if so, how, and what would be the best/easiest?
Thanks =)

A: After messing around a few days with Unity, I found this tutorial: http://www.markuszancolo.at/2015/09/integrating-unity-into-a-native-ios-app-example/ right now I think this solution is valid enough for what I want to do.
Basically I have to create a project for Unity, and create a build for Debug. This will create an iOS project for xcode and then I have to take control of the AppDelegate.

A: In UE4 you will likely need to get the engine's source in order to put in the necessary dependencies for the communication from GUI to the engine. Personally, I think it would work best if you implement custom GUI with the engine into the app, that would likely save you time and trouble. However, if native UI is necessary, then digging into UE4's source would likely be your best bet.
Please contact me if you need further assistance!


text:
Q: Post to Facebook Page with PHP as Page Admin Firstly I am aware that there are a million questions similar to this, but they are all either out of date (Facebook has changed and the instructions no longer work) or don't explain how to do specifically what I am asking.
I'm trying to register an app on Facebook so that I can autopost to the company Facebook page, of which I am an admin.
I'm trying to do this via PHP, with which I have considerable experience (PHP, not Facebook API.)
So far I have registered as a Facebook developer, made a Facebook app, got the appID and secret word, and downloaded the facebook-php-sdk from Github. I have attempted to follow a couple of tutorials but the Facebook developer/app pages have all changed and so the intructions are now invalid.
All I want to do is to be able to post automatically to my page's wall from the server via PHP, as if I posted the status update myself as the page admin. I don't understand how or why this is so difficult.
The Facebook app page has a million settings that I've never heard of and don't seem to be related, then there is no information that gives any direction to do what I want to do.
This is about as far as I've got and I've hit a wall. No idea what to do next. Facebook keeps asking me "Select how your app integrates with Facebook" but their options don't appear to include what I want, which is just to post on my own page. I don't appear to actually be able to use the app yet, as there are various settings its insisting on, like "Canvas URL", which I do not understand, etc. and then I obviously need to set permissions, yet I see no way to do this either.
What do I do?

A: Setting up an app
You are going to need to authenticate the user who has at least content creator rights on your page. So you need to choose 'Website with Facebook Login' and enter your website url.
You'll also have to enter the domain (website url without protocol)
Keep it in sandbox mode while you test it you can edit that later.
You don't really have to worry about other settings as the permissions to ask can be added directly in your php code.
"Online" Access
To logging and post directly to facebook you'll need to retreive an access token
Getting an access token
Here is a basic run down:

*

*Get user to login and allow app with appropriate permissions (manage_pages, publish_stream) if he hasn't

*Retreive user access token

*Query /me/accounts with user access token to get the page id & access token

Then all you have to do is make your API call with id & access token to post on facebook
"Offline" Access
In order to post without having to logging (usefull if you aren't the only one posting) you need a permanent extended token. So you basically should have a separate script that you'll run once to retrieve that extended token and store it.
Getting an extended access token
To be able to post without the user being logged in you need a permanent access token for your page.
Here is a basic run down:

*

*Get user to allow app with appropriate permissions (manage_pages, publish_stream)

*Retreive user access token

*Change user access token for extended user access token

Here is how I do this step (you could also use curl)
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUT_APP_SECRET&grant_type=fb_exchange_token&fb_exchange_token=OLD_TOKEN";
$accessToken = @file_get_contents($token_url);

Then

*

*Query /me/accounts with user extended access token to get the page

*Change page access token for extended access token (same code as
above)

(The last step shouldn't be necessary according to the doc as you should get an extended page token when you query /me/accounts with an extended user token but in my case it didn't work)
And you get a permanent access token that only expires if the user changes password or disallows the app. All you have to do is store it with the page's id and retreive it wherever you need an API call to post to facebook.
The php sdk is pretty well documented so you shouldn't run into any problem a google search can't fix. Look for post september 2012 threads the flow hasn't changed since neither did the php sdk much.


text:
Q: Creating index on specific JSON value inside an object array So let's say I have a varchar column in a table with some structure like:
{
   "Response":{
      "DataArray":[
         {
            "Type":"Address",
            "Value":"123 Fake St"
         },
         {
            "Type":"Name",
            "Value":"John Doe"
         }
      ]
   }
}

And I want to create a persisted computed column on the "Value" field of the "DataArray" array element that contains a Type field that equals "Name". (I hope I explained that properly. Basically I want to index the people names on that structure).
The problem is that, unlike with other json objects, I can't use the JSON_VALUE function in a straightforward way to extract said value. I've no idea if this can be done, I've been dabbling with JSON_QUERY but so far I've no idea what to do.
Any ideas and help appreciated. Thanks!

A: You could achieve it using function:
CREATE FUNCTION dbo.my_func(@s NVARCHAR(MAX))
RETURNS NVARCHAR(100)
WITH SCHEMABINDING
AS
BEGIN
   DECLARE @r NVARCHAR(100);

   SELECT @r = Value
   FROM OPENJSON(@s,'$.Response.DataArray')
   WITH ([Type] NVARCHAR(100) '$.Type', [Value] NVARCHAR(100) '$.Value')
   WHERE [Type] = 'Name';

   RETURN @r;
END;

Defining table:
CREATE TABLE tab(
  val NVARCHAR(MAX) CHECK (ISJSON(val) = 1),
  col1 AS dbo.my_func(val) PERSISTED        -- calculated column
);

Sample data:
INSERT INTO tab(val) VALUES (N'{
   "Response":{
      "DataArray":[
         {
            "Type":"Address",
            "Value":"123 Fake St"
         },
         {
            "Type":"Name",
            "Value":"John Doe"
         }
      ]
   }
}');

CREATE INDEX idx ON tab(col1);   -- creating index on calculated column

SELECT * FROM tab;

db<>fiddle demo

A: You could use a computed column with PATINDEX and index that:
CREATE TABLE foo (a varchar(4000), a_ax AS (IIF(PATINDEX('%bar%', a) > 0, SUBSTRING(a, PATINDEX('%bar%', a), 42), '')))

CREATE INDEX foo_x ON foo(a_ax)

A: You could use a scalar function as @Lukasz Szozda posted - it's a good solution for this.
The problem, however, with T-SQL scalar UDFs in computed columns is that they destroy the performance of any query that table is involved in. Not only does data modification (inserts, updates, deletes) slow down, any execution plans for queries that involve that table cannot leverage a parallel execution plan. This is the case even when the computed column is not referenced in the query. Even index builds lose the ability to leverage a parallel execution plan. Note this article: Another reason why scalar functions in computed columns is a bad idea by Erik Darling.
This is not as pretty but, if performance is important than this will get you the results you need without the drawbacks of a scalar UDF.
CREATE TABLE dbo.jsonStrings
(
  jsonString VARCHAR(8000) NOT NULL,
  nameTxt AS (
    SUBSTRING(
      SUBSTRING(jsonString,
        CHARINDEX('"Value":"',jsonString,
          CHARINDEX('"Type":"Name",',jsonString,
            CHARINDEX('"DataArray":[',jsonString)+12))+9,8000),1,
      CHARINDEX('"',
        SUBSTRING(jsonString,
          CHARINDEX('"Value":"',jsonString,
            CHARINDEX('"Type":"Name",',jsonString,
              CHARINDEX('"DataArray":[',jsonString)+12))+9,8000))-1)) PERSISTED
);

INSERT dbo.jsonStrings(jsonString)
VALUES
('{
   "Response":{
      "DataArray":[
         {
            "Type":"Address",
            "Value":"123 Fake St"
         },
         {
            "Type":"Name",
            "Value":"John Doe"
         }
      ]
   }
}');

Note that, this works well for the structure you posted. It may need to be tweaked depending on what the JSON does and can look like.
A second (and better but more complex) solution would be to take the json path logic from Lukasz Szozda's scalar UDF and get it into a CLR. T-SQL scalar UDFs, when written correctly, do not have the aforementioned problems that T-SQL scalar UDFs do.


text:
Q: Positioning text slightly more to the right I'm trying to place the text a little bit more to right. Tried much of position codes already, but the CSS doesn't read the code, I think.

*

*Screenshot: https://gyazo.com/6f9cc34d8ed6d33fde401b6317be3a3e
.portal .icons a {
    position: relative;
    margin-bottom: 15px;
    top: 0px;
    transition: all 0.5s ease;
    text-decoration: none;
    color: rgba(215, 213, 216, 0.4);
    font-family: ZCOOL QingKe HuangYou;
    font-size: 40px;
    text-shadow: 2px 2px 2px rgba(215, 213, 216, 0.4);
}

A: since you added postition:relative you should add left: value_of_how_much_you_wnt_to_push_it_to_the_right

A: Try This :
.portal .icons a {
position: relative;
margin-bottom: 15px;
top: 0px;
//add this
left : 100% ;
transition: all 0.5s ease;
text-decoration: none;
color: rgba(215, 213, 216, 0.4);
font-family: ZCOOL QingKe HuangYou;
font-size: 40px;
text-shadow: 2px 2px 2px rgba(215, 213, 216, 0.4);

}


text:
Q: Angular tab group with asynchronously loading tab contents. Contents must be another component I am trying to pass component tag from my ts file but getting it as a string. Please help
chat-list.component.ts
export interface ExampleTab {
  label: string;
  content: string;
 }

  asyncTabs: Observable<ExampleTab[]>;

constructor() {
this.asyncTabs = Observable.create((observer: Observer<ExampleTab[]>) => {
  setTimeout(() => {
    observer.next([
      {label: 'First', content: '<app-chart-finance></app-chart-finance>'},
      {label: 'Second', content:'<app-chart-finance></app-chart-finance>'},
      {label: 'Third', content: '<app-chart-finance></app-chart-finance>'},
    ]);
  }, 1000);
});

chat-list.component.html
<ng-container *ngIf="(asyncTabs | async) === null">
Loading tabs...
</ng-container>
<mat-tab-group>
 <mat-tab *ngFor="let tab of asyncTabs | async">
  <ng-template mat-tab-label>{{tab.label}}</ng-template>
  {{table.content}}
 </mat-tab>
</mat-tab-group>

I am getting {{table.content}} as a string. But I want to show the dom of the particular component. I declare content as a string. Maybe that is why I am getting it as a string. So what kind of changes I need to make to get my desired output.
Thank you all for your support.


text:
Q: How to combine a list with a list of sublists i hope some of you can support to solve my problem, i need to work on data in the following way, where the length of each of the lists or sublists is equal. As an example i want to share the data-pattern with you:
list1={a,b,c};
list2={{d,e,f},{g,h,i},......} (in reality the number of sublists in list2 is about 30)
data=list2[[1]]

the goal is now to combine these lists in the following form
{ {{a,d},{b,e},{c,f}}, {{a,g},...} ...} .

The next step to plot it or to create a fit-formula. The values of list1 should be always plotted as the x-Data.
I created some of the most interesting datasets as follows: `
plottedList=Table[{list1[[k]], data[[k]]}, {k, 1, Length[data]}]
ListPlot[plottedList]

My Problem is that i now would need to plot all of the data-pairs and combine the data to create the lists which i can find a linear or nonlinear fit.

I hope you can give me some advice,
Best Chris!

A: A minor variation based on @kglr's answer.
list1 = {a, b, c};
list2 = {{d, e, f}, {g, h, i}};
MapThread[List, {list1, #}] & /@ list2

Using Transpose:
Transpose[{list1, #}] & /@ list2

Result:

{{{a, d}, {b, e}, {c, f}}, {{a, g}, {b, h}, {c, i}}}

A: list1 = {a, b, c};
list2 = {{d, e, f}, {g, h, i}};

Map[Thread[{list1, #}] &] @ list2

{{{a, d}, {b, e}, {c, f}}, {{a, g}, {b, h}, {c, i}}}

A: Inner[{#2,#1}&,list2,list1,List]

(* {{{a, d}, {b, e}, {c, f}}, {{a, g}, {b, h}, {c, i}}} *)

A Slot-free version
J. M. can't deal with it  (in a comment) gives the following neat modification:
Inner[ReverseApplied[List], list2, list1, List]

Lists
list1 = {a, b, c};
list2 = {{d, e, f}, {g, h, i}};


text:
Q: securing files by putting them behind a secured network connection I'm developing an desktop application in JAVA (J2SE).
my App. stores some data about users.
the App. is multi user and will be installed on a single station.
each user can have some documents that should be stored in file-system (e.g. image, audio, ...)
I need to protect these files from be accessed directly by unauthorised users.
Users are defined in app itself (i need files be accessible only via application)
How can I protect these files from unauthorised access?
I thought about storing files in another system and access them via network.
How Can I do this (store/ retrieve files in a secured network computer) in JAVA?
Is this a good method?  any better solution?
Thanks
EDIT:
decription:
My users are defined in application: all users use same computer; all users login with the same username in OS; each user logs in app with their own user/pass; each user should have access to files that application decides.
So users must not be able to open a file-manager and traverse through directories that files are stored in & copy them (while doesn't have access to them)

A: Instead of rolling out your own security solution - which will be cumbersome, almost certainly buggy, and with a high probability vulnerable to various attacks - simply use the Operating System's filesystem permission.
The easiest way to do that is to write your user data to the home directory of the current user. Other users will not be able to access it unless the user explicitly configures the directory's permissions to allow them.
If you want, you can also further restrict the permissions of your directory.

A: Since all users use the same OS login account, it is impossible to use OS's facilities to enforce access control, since the OS recognizes everyone as one person. I can only think of one (not-so-good, or quite bad actually) solution that doesn't require another computer: encrypt the files with each of the user's password. However, this means that all the files have to be re-encrypted every time the user changes password, which introduces unacceptable delays and uses a lot of computational power.
There are plenty of other methods to hide the information from the user and only allow access from your program. Hiding can prevent most mediocre users from accessing data, but determined people with programming skill will be able to make the data accessible. A simple example is to xor all the bytes in the program, and/or permute the bytes with a number of fixed pattern. If the data is not that critical, this is a possible "solution".
I am not sure if there are any other method without requiring another computer.
So that leaves only the option of storing the information on a separated computer. I think it is possible, but I don't know the details here.

Then there is this problem: user A opens a file from his app account, work with it, then he logs out of the app account, and logs out of common OS account, then user B logs into the common OS account. You have to make sure that after user A logs out of app account, user B cannot see the file user A was working on.
I am not sure if this should be taken care of the app or not.

A: One option would be to use SFTP. This way you can leverage the SFTP security features. But off course this will need some plumbing code to be written around it.


text:
Q: npm install -g @angular/cli not executing
I've tried executing the command npm install -g @angular/cli@latest and npm install -g @angular/cli. Both of them are giving this error.

A: i think it's related to compatibility between node and npm versions, You can try NVM for windows
and then you can use it to install a specific node version and it will install the compatible npm version with it
nvm install 12.8.1

you can install multiple versions of node if you want and switch between them
nvm list

for example you can switch to use 8.11.3 like this:
nvm use 8.11.3

imagine that i want to install node 13.3 with nvm install 13.3, nvm will install npm 6.13.1 with it

Please have a look a lon on the list of releases her https://nodejs.org/en/download/releases/

A: please check with your internet connectivity, proxy or npm registry. It look like it is not able to reach to npm repo to bring the angular cli


text:
Q: How to get value of 'this' with nested {{#each}} in Meteor I've got a simple list of documents that are generated with the {{#each}} iterator:
{{#each Teachers}}
    {{FullName}}
{{/each}}

When a user clicks on one of the teachers listed, a new page is routed to that teacher's profile page and we have access to that teacher's document with 'this' so I can say:
var phone = this.phoneNumber;

Now, within that teacher's profile page another list is generated of that teacher's students:
{{#each Students}}
  {{FullName}}
{{/each}}

When the user clicks on a student in that list (on that teacher's page), I'm trying to get access to the student document by using 'this' again. So if I wrote:
Template.TeacherTemplate.events({
  'click #student-name': function () {
    console.log(this.FullName);
}

I'd expect to see the student's full name in the console. But it's still referencing the teacher's full name here. How can I get the reference to the student when clicking the student list?

A: Make another template for student.
<template name='student'>
  {{FullName}}
</template>

Then use student template in each loop.
{{#each Students}}
  {{> student}}
{{/each}}

Template.student.events({
  'click': function(){
    console.log(this.FullName);
  }
});


text:
Q: Is there a way for get the inner value of this Lambda expression I have an "ID" inside of lambda expression, but Im not sure how to to get the value to send it to a main controller.
@Html.HiddenFor(model => model.id)

I have the ID inside of that lambda expression, I tried getting the id directly from the model "model.id".
I tried creating a new variable like this:
var id1 =@Html.HiddenFor(model => model.id)

But I get this error :
A potentially dangerous Request.Path value was detected from the client (<).
Code
@Html.HiddenFor(model => model.id)

@Html.ActionLink("Approve", "ControllerAprove", new {id = model.id}, new { @class = "btn btn-primary btn-large" })

1 - If I try to use
new {id = model.id} the value of id its equal to 0.
2 - If I try:
@Html.HiddenFor(model => model.id)

@{var ID1 = @Html.HiddenFor(model => model.id);}

@Html.ActionLink("Approve", "ControllerAprove", new {id =ID1}, new { @class = "btn btn-primary btn-large" })

Then I get A potentially dangerous Request.Path value was detected from the client (<).