text:
Q: How to reload environmental variables in .profile using source for entire session? So I need to reload my profile after making changes (this time due to a typo). I run source ~/.profile and everything works perfectly fine.
However the source command only applies to that terminal session. This means I'm running the command every time I open up a new terminal. I want to find a way to apply the .profile/environmental variables to the entire user session without logging out, not just the current terminal.
Is there a package or command that can execute this type of change by reloading the profile like it loaded on login?
EDIT:
To clarify that it is not a duplicate I don't want to use:
source ~/.profile

or
. ~/.profile

As they only effect changes on one terminal session. I want to effect changes across all started terminals from my user session. I already have changes in the current terminal session using those commands. I need them in newly opened terminal after I run the command (which to clarify I don't currently have. the changes are only effecting the current terminal and my question is to effect these changes across multiple terminals

A: You cannot. Environment variables are kept in each shell's per-process memory. Other processes (other shells, like the one you want to change eveything) cannot access this memory. Nor does bash listen to a socket for getting updates.
Reread man bash, especially the INVOCATION section.
~/.profile is more a ksh startup file. However, you could put source $HOME/.profile in your ~/.bashrc.


text:
Q: Get checkboxs value with Jquery return wrong values sometimes but not everytime I try to get the checkbox checked values,
It "works" not really well, sometimes I have the right value, sometime not, could you explain me why and how I can fix this ?
The purpose is at this end to build an array of all the values checked
Here a snippet :

$( "input" ).on( "click", function() {
  alert('test : ' + $( "input:checked" ).val() + " is checked!"  );
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

          <input class="form-check-input" type="checkbox" id="inlineCheckbox1" name="abc" value="all">
          All

          <input type="checkbox" id="inlineCheckbox2" name="abc"  value="businessrules">
          Business Rules

          <input  type="checkbox" id="inlineCheckbox3" name="abc" value="scriptinclude">
          Script Include

          <input  type="checkbox" id="inlineCheckbox4" name="abc" value="schedulejobs">
          Scheduled Jobs

          <input  type="checkbox" id="inlineCheckbox5" name="abc" value="uiaction">
          UI Action

          <input  type="checkbox" id="inlineCheckbox6" name="abc" value="uipolicies">
          UI Policies

          <input  type="checkbox" id="inlineCheckbox7" name="abc" value="uimacro">
          UI Macro

          <input type="checkbox" id="inlineCheckbox8" name="abc" value="uipage">
          UI Page

Thanks a lot for your help

A: Your selector
$( "input:checked" )

selects an array of all input elements that are ckecked. By then trying to retrieve the value of that selection with
$( "input:checked" ).val()

you end up always getting the value of the first element in that array.
If you want to output the value of all checked elements you need to iterate over that array and collect all values:

$( "input" ).on( "click", function() {
    let checkedValues = $( "input:checked" ).map(function() {
        return $(this).val();
    }).get().join(', ');
    alert('Checked: ' + checkedValues   );
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

          <input class="form-check-input" type="checkbox" id="inlineCheckbox1" name="abc" value="all">
          All

          <input type="checkbox" id="inlineCheckbox2" name="abc"  value="businessrules">
          Business Rules

          <input  type="checkbox" id="inlineCheckbox3" name="abc" value="scriptinclude">
          Script Include

          <input  type="checkbox" id="inlineCheckbox4" name="abc" value="schedulejobs">
          Scheduled Jobs

          <input  type="checkbox" id="inlineCheckbox5" name="abc" value="uiaction">
          UI Action

          <input  type="checkbox" id="inlineCheckbox6" name="abc" value="uipolicies">
          UI Policies

          <input  type="checkbox" id="inlineCheckbox7" name="abc" value="uimacro">
          UI Macro

          <input type="checkbox" id="inlineCheckbox8" name="abc" value="uipage">
          UI Page

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I start a new transaction on an existing Gnosis Safe from my react app? Currently I have a React app which connects to a Metamask wallet. On clicking a 'Transfer' button, it transfers some ethers from the connected Metamask wallet to the one input by the user. All of this works fine and is pretty straightforward. It looks something like this (I am using ethers.js):
// fetch signer from connected metamask account
const signer = new ethers.providers.Web3Provider(ethereum).getSigner()
const contract = new ethers.Contract(contractAddress, ERC20ABI, signer)

// create a new transaction - that's it! so simple!
const txResponse = await contract.transfer(_recipientWalletAddress, utils.parseUnits(_userinput).toString())

Now, I want the same functionality but instead of transferring from the connected Metamask wallet, I want to connect to an existing Gnosis Safe and transfer funds from the safe to a recipient. I already have a test Gnosis Safe set up on gnosis-safe.io over Goerli Testnet with 3 owners. I have the Safe address. I have the addresses of the owners.
In my app, I have connected my app to the test Gnosis Safe using WalletConnect.
Now, I want that I click a button, enter a recipient address and submit the form. This should create a new transaction on the test Gnosis Safe. And then on the Gnosis Safe, the owners can approve/reject the created transaction. I am struggling with this part.
This is what I've tried
import Safe from '@gnosis.pm/safe-core-sdk'
import { ethers, utils } from 'ethers'
import EthersAdapter from '@gnosis.pm/safe-ethers-lib'

// have all addresses here
const gnosisSafeAddress = '0xsafexaddress'
const gnosisSafeOwners = ['0xsafexownerx1', '0xsafexownerx2', '0xsafexownerx3']

// create a ethers provider over goerli network
const provider = new ethers.providers.JsonRpcProvider(`https://goerli.infura.io/v3/${infuraAPIKey}`);

// create signer using the provider and private key of the one of the gnosis safe owner
const signer = new ethers.Wallet(PRIVATE_KEY_OF_SAFE_OWNER_1, provider);

// create connection to safe using the gnosis safe address
const ethAdapter = new EthersAdapter({ ethers, signer });
const safeSdk = await Safe.create({ ethAdapter, safeAddress: gnosisSafeAddress });

// create a transaction
const transaction = {
   to: _recipientWalletAddress,
   value: utils.parseUnits(_userinput).toString(),
   data: '0x',
};

const safeTransaction = await safeSdk.createTransaction(transaction);

This does not work at all. I logged every step and every variable in between is empty objects. Kindly help me understand what I am doing wrong. I am extremely confused reading the Gnosis SDK repos.
I don't want to deploy a test Gnosis Safe programmatically. I don't want to create a Safe app. I just want to create a transaction, programmatically, on Gnosis Safe (a wallet) to transfer funds, like I do for metamask.

A: There are not many good resources on how to interact with Safes from react. I suggest trying to write a script in node to grok the flow first. I created a script here that deploys and sends a transaction from the safe
to do the same thing in react (without using the transaction relayer service) you can do the following
import React, { useEffect, useState } from 'react'
import { Button } from "@nextui-org/react";
import { ethers } from "ethers";
import { useSigner } from 'wagmi'
import EthersAdapter from '@gnosis.pm/safe-ethers-lib'
import Safe, { SafeFactory } from '@gnosis.pm/safe-core-sdk'
import { SafeTransactionDataPartial, TransactionResult, SafeTransaction } from '@gnosis.pm/safe-core-sdk-types'

const threshold: number = 1;
const owners = ['0x0533F9d586ABd3334a0E90cA162602D6574F0493']

const safe = () => {
  const [gnosisLoaded, setGnosisLoaded] = useState<boolean>(false)
  const [safeDeployed, setSafeDeployed] = useState<boolean>(false)
  const [safeAddress, setSafeAddress] = useState<string>('')
  const { data: signer } = useSigner()
  const [safeSdk, setSafeSdk] = useState<Safe | null>(null)
  const [safeFactory, setSafeFactory] = useState<SafeFactory | null>(null)

  const deploySafe = async () => {
    const safeSdk = await safeFactory?.deploySafe({ safeAccountConfig: { owners, threshold } })
    if (!safeSdk) return
    setSafeSdk(safeSdk)
    setSafeAddress(safeSdk.getAddress())
    setSafeDeployed(true)
  }

  const sendSafeTransaction = async () => {
    const to = await signer?.getAddress()
    const transaction: SafeTransactionDataPartial = {
      to,
      value: "1",
      data: '0x',
    };

    const safeTransaction: SafeTransaction = await safeSdk?.createTransaction({ safeTransactionData: transaction });
    const executeTxResponse: TransactionResult = await safeSdk?.executeTransaction(safeTransaction)
    await executeTxResponse.transactionResponse?.wait()
  }

  useEffect(() => {
    if (!signer) return

    const setupGnosis = async () => {
      const ethAdapter = new EthersAdapter({ ethers, signer })
      const safeFactory = await SafeFactory.create({ ethAdapter })
      setSafeFactory(safeFactory)
      setGnosisLoaded(true)
    }

    setupGnosis()
  }, [signer])

  return (

      {gnosisLoaded ?
gnosis loaded
 :
gnosis loading...
}
      {safeDeployed ?
safe deployed: {safeAddress}
 :
safe not deployed
}
      <Button disabled={!gnosisLoaded} onClick={() => deploySafe()}>
        Deploy Safe
      </Button>
      <Button disabled={!safeDeployed} onClick={() => sendSafeTransaction()}>Send Transaction</Button>

  )
}
export default safe


text:
Q: Room doesn't execute AddNewCallback I am trying to init data with RxJava2, Dagger2 and Room and MVP in Android, but Android doesn't execute my room callbacks.
This is my method that creates database, and this is what I see in logs:
public synchronized static AppDatabase getInstance(Context context) {
    if (INSTANCE == null) {
        INSTANCE = buildDatabase(context);
   }
   return INSTANCE;
}

private static AppDatabase buildDatabase(Context context) {
    Log.i("jestem", "builddatabase");

    RoomDatabase.Callback callback = new Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            Log.i("jestem", "oncreatebuildda22tabase");
            super.onCreate(db);
          Single.just(getInstance(context).initData());
        }

        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db) {
            getInstance(context).onOpenDb();
            super.onOpen(db);
        }
    };

    return Room.databaseBuilder(context,
            AppDatabase.class,
            "pijatyka.db")
            .addCallback(callback)
            .build();}

public static void onOpenDb() {
    Log.i("jestem", "onopendb");
    hasFinishedCreating = true;

}

public boolean initData() {
    Log.i("Im here", "oncreatebuilddatabase");
    for (Cards card : DataGenerator.initCards()
            ) {
        myDAO().insertCard(card);
    }
    for (Awards award : DataGenerator.initAwards()
            ) {
        myDAO().insertAwards(award);
    }
    hasFinishedCreating = true;
    return true;
}

But I don't see any of this in logs, and I don't know why...inside the function onCreate and onOpen
This is my activity module:
@Module
public class StartModule {

    private final StartActivity activity;

    public StartModule(StartActivity activity) {
        this.activity = activity;
    }

    @Provides
    @StartScope
    public Activity activityProvides(){
        return  activity;
    }

    @Provides
    @StartScope
    public  StartView view(){
        return new StartView(activity);
    }

    @Provides
    @StartScope
    public StartPresenter presenter(StartView view, StartModel model){
        return new StartPresenter(view, model);
    }

    @Provides
    @StartScope
    public StartModel model(AppDatabase database){
        return new StartModel(activity, database);
    }
}

And my application module
@Module
public class MyAppModule {
    private final Context context;

    public MyAppModule(Application application){
        context = application.getApplicationContext();
    }

    @MyAppScope
    @ApplicationContext
    @Provides
    public Context context(){
        return context;
    }

    @MyAppScope
    @Provides
    public AppDatabase appDatabase(@ApplicationContext Context context){
         return AppDatabase.getInstance(context);
    }

    @Provides
    @MyAppScope
    public MyDAO providesMyDao(AppDatabase database){
        return database.myDAO();
    }

}

A: The code from just won't be executed until you subscribe to the Single object, so change:
Single.just(getInstance(context).initData());

to
Single.just(getInstance(context).initData())
    .subscribeOn(Schedulers.io())   // init Data off main thread
    .subscribe();                   // pass some results handler, if you need

Example of result handlers:
Single.just(getInstance(context).initData())
        .subscribeOn(Schedulers.io())
        .subscribe(result -> {
            if(result)
                System.out.println("Init successful");
            else
                System.out.println("Init unsuccessful");
        }, error -> {
            System.out.println("Error occurred: " + error);
        });

A: '   private Disposable isFinishedCreatingDataBase(){
      //  return model.hasFinishedCreating()
        return Single.just(appDatabase.hasFinishedCreating)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .delay(2, TimeUnit.SECONDS)
                .repeat()
                .subscribe(n -> {
                    if(n==true){
                        startNewActivity();
                    }
                    Log.i("show", String.valueOf(n));
                }); '

i subscribe them, but in the presenter sorry :D im not write this here..
:/


text:
Q: Laravel 5.4 image resizing issue I have a problem on resizing image in laravel 5.4
I am using the following code to resize image:
    $sample_front_image = $request->file('sample_front_image');
    $input['sample_front_image'] = $sample_front_image->getClientOriginalName();
    $image_resize = Image::make($sample_front_image->getRealPath());
    $image_resize->resize(120, 120);
    $image_resize->save(public_path($thumbnail_dir, $input['sample_front_image']));

But I am getting the following error showing below:

It seems that above code is working fine for previous laravel versions but is not working on 5.4 version. Any Solution?

A: It is because Intervention is not able to find the image you are passing it for resizing. You are providing temporary image path to the Image::make() instead of the actual path.
So first you have to upload the image using store() to somewhere and then need to provide that image full path to the Image::make().
Hope this helps.


text:
Q: Flutter Location package generates platform exception on call to serviceEnabled() Flutter 2.0.6, Location package 4.1.1.
This snippet of code...
  try {
    _serviceEnabled = await location.serviceEnabled();
  } on PlatformException catch (err) {
    print ("Platform exception calling serviceEnabled(): $err");
    _serviceEnabled = false;
  }

Generates:  Platform exception calling serviceEnabled(): PlatformException(SERVICE_STATUS_ERROR, Location service status couldn't be determined, null, null)
But here's the interesting part:  this error only comes up when I run a release build on my Samsung Galaxy S8.   If I run a debug build on the S8, or if I run either a release or a debug build on an android emulator, no error is thrown.  I've tried a few different emulator configurations, specifically one configured as closely to the S8 -- Android version 9 (SDK 28), and same screen size.
Any suggestions for how to investigate why this is happening would be greatly appreciated.

A: initLocation() async {
    try {
      _serviceEnabled = await location.serviceEnabled();
    } on PlatformException catch (err) {
      print("Platform exception calling serviceEnabled(): $err");
      _serviceEnabled = false;

      // location service is still not created

      initLocation(); // re-invoke himself every time the error is catch, so until the location service setup is complete
 }   }

call initLocation() from initState()
@override void initState() {
super.initState();
initLocation(); }

problem is related with some Android timeout processes, so the recursive call
credit-issue thread


text:
Q: Raw mouse input doesn't work in VMware Player Windows I been following jpres tutorial trying to get raw mouse input data.
When the app runs on VMWare Player windows I do not get the expected data.
e.x:
In normal Windows: x: 0, y: 1
in VMWare: x: 53081, y: 32010
Is there something wrong with the VM or is it the code itself?
link to jpres youtube tutorial: https://www.youtube.com/watch?v=M61AjhVDFS8&list=PLcacUGyBsOIBlGyQQWzp6D1Xn6ZENx9Y2&index=8&ab_channel=Jpres
link to jpres github tutorial: https://github.com/Pindrought/DirectX-11-Engine-VS2017/tree/Tutorial_7
How code looks like roughly:
switch (uMsg){
   case WM_INPUT:
   {
    UINT dataSize;
    GetRawInputData(reinterpret_cast<HRAWINPUT>(lParam),
        RID_INPUT,
        NULL,
        &dataSize,
        sizeof(RAWINPUTHEADER));

    if (dataSize > 0){
        std::unique_ptr<BYTE[]> rawdata = std::make_unique<BYTE[]>(dataSize);
        if (GetRawInputData(reinterpret_cast<HRAWINPUT>(lParam),
                    RID_INPUT,
                    rawdata.get(),
                    &dataSize,
                    sizeof(RAWINPUTHEADER))
                    == dataSize)
                {

                RAWINPUT* raw = reinterpret_cast<RAWINPUT*>(rawdata.get());
            if (raw->header.dwType == RIM_TYPEMOUSE){
               mouse->onMouseMoveRaw(raw->data.mouse.lLastX, raw->data.mouse.lLastY);
            }
        }
    }
   return DefWindowProc(hwnd, uMsg, wParam, lParam);
   }

I tried to run the code on multiple computers that run windows(no VM) and that works.


text:
Q: Creating a Python class that holds its value as an upper case string doesn't work Why doesn't this work?
>>> class A (unicode):
...     def __init__ (self, value):
...         super(unicode, self).__init__(str(value).upper())
...
>>> assert A('hello') == u'HELLO'

Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    assert A('hello') == u'HELLO'
AssertionError
>>>

I know that without the init method initializing the object would default to the unicode classes init method (thank you MRO) and I know that my init method is the one being called, however it doesn't seem to want to work.  Even when I add an extra line and explicitly set the value of the value parameter to upper it still doesn't want to work.
Although I can (and probably will have to) define the repr and str special classes in order to get the desired effect, I'm a little curious as to why this doesn't work.
Thanks in advance.

A: unicode are immutable object use __new__ instead of __init__:
class A (unicode):
    def __new__ (cls, value):
       return unicode.__new__(cls, str(value).upper())

print A('hello')
u'HELLO'

A: Instead of super(unicode, self), you probably want super(A, self) - the former is object.__init__.
Additionally, since unicode objects are immutable, __init__ does nothing. Instead of the regular initialization with __init__ (which would also prevent interning), the constructor you want to override is __new__:
class A (unicode):
    def __new__(cls, value):
        return super(A, cls).__new__(cls, str(value).upper())


text:
Q: How to dynamically query for a column name? Consider the following piece of SQL code for a PostgreSQL DBMS (9.3):
SELECT
    column_name, (SELECT count(*) FROM _TABLE_NAME_ WHERE column_name = 'X')
FROM
    information_schema.columns
WHERE
    table_schema = '_SCHEMA_NAME_'
AND
    table_name = '_TABLE_NAME_';

I want to use the retrieved column_names from the outer query in the inner query as column names (meta). Is there a way to do this in one SELECT statement (multiple inner SELECT statements are ok too)?
Example:

A: You don't need meta tables, you need an unpivot query. With a reasonably recent pg you can achieve it with JSON functions like this:
SELECT key
      ,count(*) FILTER (WHERE value = 'X')
FROM  _TABLE_NAME_
      ,json_each_text(row_to_json( _TABLE_NAME_)) AS unpivot
GROUP BY key;

A: This is not my work. I asked a colleague and after Jakub Kania's idea with json_each_text and row_to_json he came to the following solution which exactly answers my question.
SELECT
    k, sum((v = 'X')::INT)
FROM
(
    SELECT
        (json_each_text(row_to_json(_TABLE_NAME_WITHOUT_SCHEMA_))).KEY AS k,
        (json_each_text(row_to_json(_TABLE_NAME_WITHOUT_SCHEMA_))).VALUE AS v
    FROM
        _TABLE_NAME_
) AS tmp
GROUP BY k;


text:
Q: follow of curl for java i want how to follow the link...
for example the link :  http://example.com/hi.php
this will redirect another page to http://example.com/vi.php
then this will redirect another page to http://example.com/ji.html
so i need to get the page link "http://example.com/ji.html"
i think, i cant in java.. so have possible in java curl?
thanks advance

A: See
Apache Http Client 4.0 using parameter "http.protocol.handle-redirects"


text:
Q: How to update Date() every second? I am trying to make a program that updates currentTime every second so that in the console it will go 1s, 2s, 3s, 4s and so on.
public static void main(String[] args) throws InterruptedException{
    OSpanel runner = new OSpanel();
    runner.currentTime();
}

public static void currentTime() throws InterruptedException{
    if(true) {
        Date currentTime = new Date();
        while(true) {
            Thread.sleep(1000);
            System.out.println(currentTime);
            Thread.sleep(1000);
            System.out.println(currentTime);
        }
    }
}

A: java.time
The java.util Date-Time API is outdated and error-prone. It is recommended to stop using it completely and switch to the modern Date-Time API*.
You can use Instant#now to get the current instant of time. In order to get it every second, you can use ScheduledExecutorService#scheduleWithFixedDelay e.g.
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        Executors.newScheduledThreadPool(1)
            .scheduleWithFixedDelay(
                () -> System.out.println(Instant.now()),
                0,
                1,
                TimeUnit.SECONDS
            );
    }
}

Output from a sample run:
2021-10-03T13:53:42.462768Z
2021-10-03T13:53:43.469758Z
2021-10-03T13:53:44.470316Z
...

ONLINE DEMO
An Instant represents an instantaneous point on the timeline, normally represented in UTC time. The Z in the output is the timezone designator for a zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
Note: If you want to print just the running second, replace the print statement with the following:
System.out.println(ZonedDateTime.now(ZoneOffset.UTC).getSecond() + "s")

Learn more about the modern Date-Time API from Trail: Date Time.

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project. Android 8.0 Oreo already provides support for java.time.

A: You are updating currentTime outside of the while loop - you are outputting the date to the console every second but you are not updating the time.
Try this:
Main.java
public static void main(String[] args) throws InterruptedException{
    OSpanel runner = new OSpanel();
    runner.currentTime();
}

OSpanel.java
public void currentTime() throws InterruptedException{
        int counter = 1;
        while (true) {
            System.out.println(counter + "s");
            Thread.sleep(1000);
            counter++;
        }
    }
}

A: This will create a thread pool with one thread which will execute the lambda printing the number of seconds since the program started once every second.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class SOAnswer {
    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        long start = System.currentTimeMillis();
        executorService.scheduleAtFixedRate(() -> System.out.println(String.format("%ds", (System.currentTimeMillis() - start) / 1000)), 0, 1, TimeUnit.SECONDS);
    }
}

A: Duration
Adding to the good Answer by Avinash, let me show the use of Duration to track elapsed time.
Record a starting moment.
Instant start = Instant.now() ;  // Capture the current moment as seen in UTC.

At any other moment, calculate elapsed time on a scale of hours-minutes-seconds using the java.time.Duration class.
Duration d = Duration.between( start , Instant.now() ) ;

Generate text representing that elapsed time in standard ISO 8601 format: PnYnMnDTnHnMnS .
String output = Duration.toString() ;

PT21s

To generate text in a custom format, write a method that accesses the various parts. Call toHoursPart, toMinutesPart, etc. Put those parts together in whatever way you desire.
Pulling this all together, in the code of that other Answer, change this line:
() -> System.out.println( Instant.now() ) ,

… to this line:
() -> System.out.println( Duration.between( start , Instant.now() ).toString() ) ,

… or call your custom formatting method.


text:
Q: Правильный вывод showMiniCart Нужна помощь, есть функция
function showMiniCart(){
    //показываю содержимое корзины
    var out ='';
    for (var key in cart) {
        out += Object.keys(cart).reduce((total, key) => total += cart[key], 0);
    }
    $('#mini-cart').html(out);
}

Проблема в том, что выводит она не совсем, верно то, что хотелось, а именно, в корзину попадет:
Если добавлю 1 товар то все нормально складывает, но при добавлении 2 товара, результат складывается и выводит рядом еще раз.
Пример: 1 товар - вывод 1, 2 товара - вывод 22, 3 товара - выводит 333.

A: Уберите + в строке
for (var key in cart) {
    out = Object.keys(cart).reduce((total, key) => total += cart[key], 0);
}

вы конкатенируете строки, а исходя из задачи у вас должно получаться новое значение


text:
Q: PDO exception is : "No Database Connection" I can't find any way to connect to database with pdo; I tried the folowing syntax .
I have php7 and and pdo support mysql database
ConnectDb class:
class ConnectDb {
    private $username = "admin";
    private $password = "passw";
    private $connection = NULL;

    protected function __construct($dbname)
    {
        try
        {
            $connection = new PDO("mysql:host=" . "127.0.0.1" . ";dbname=" . $dbname . ";charset=utf8;",$this->username,$this->password,array(PDO::ATTR_PERSISTENT => true));
            $connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        }
        catch (PDOException $exception){
            echo $exception->getMessage();
        }
    }

    protected function getConnection()
    {
        return $this->connection;
    }
}

Insert data class
class InsertDb extends ConnectDb
{
    function __construct($dbname)
    {
        parent::__construct($dbname);
        $this->insert();
    }

    private function insert()
    {
        if ($this->getConnection() !== NULL) {
            $savequer = "INSERT INTO customer (first_name, last_name, email, password) VALUES (?,?,?,?)";
            $savedPdo = $this->getConnection()->prepare($savequer);
            $savedPdo->execute(array($_POST['firstName'], $_POST['lastName'],$_POST['email'], $_POST['password']));
        } else {
            echo "No Database Connection";
        }
    }
}

and my object
new InsertDb("tamrin01");

No Database Connection

A: In get_connection function you return class members connection. but in constructor you are using new variable to create a database connection.
It will be like.
protected function __construct($dbname)
    {
        try
        {
          //Create a database connection with class member connection. Don't use new variable $connection.
            $this->connection = new PDO("mysql:host=127.0.0.1;dbname=$dbname;charset=utf8;",$this->username,$this->password,array(PDO::ATTR_PERSISTENT => true));
            $this->connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        }
        catch (PDOException $exception){
            echo $exception->getMessage();
        }
    }


text:
Q: Getting undefined when to add a data node in replica set in mongodb from Node.js I am trying to add a data node in replica set in MongoDB from Node.js but it is not adding the data node into the replica set
This is my code:
var Db = require('mongodb').Db,//The modules importing
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSet = require('mongodb').ReplSet,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    assert = require('assert');

//The ip address of my machine and port number
MongoClient.connect('mongodb://192.168.0.10:27217/test', function(err, db) {
    console.log(".....");

    // Use the admin database for commands
    var adminDb = db.admin();
    console.log(".....Going");

    // Default replica set conf
    var conf = {
                _id: "rpl0",
                members: [
                    {
                     _id: 2,
                     host: "192.168.0.10:27217"
                    },
                    {
                      _id: 2,
                      host: "192.168.0.10:27317"
                    },
                    {
                      _id: 3,
                      host: "192.168.0.10:27417"
                    },
                    {
                      _id: 4,
                      host: "192.168.0.7:27017"
                    }
             ]
        };
    //The command for adding the member
       adminDb.command({replSetConfig: conf}, function(err, info) {
            console.log(info);
        });
    })

This is what I am getting the output:
....
.....Going
undefined

I don't understand what wrong I am doing.


text:
Q: Using a struct from a different library in Cython I am trying to call a C function in Cython and the header looks like this:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <ctype.h>
#include <unistd.h>
#include <math.h>

#include <apriltag.h>
#include <tag36h11.h>

#include <common/getopt.h>
#include <common/image_u8.h>
#include <common/image_u8x4.h>
#include <common/pjpeg.h>
#include <common/zarray.h>

apriltag_detection_t* scan_frame(int width, int height, uint8_t* data);

As you can see, I want to return an array of structs, which are type defined to be apriltag_detection_t. According to the documentation, in order to be able to use this in Cython, I must define some sort of pxd file which is essentially a copy of header.
However, apriltag_detection_t is a type that is already defined in apriltag.h. Furthermore, apriltag_detection_t has members that are already defined in apriltag.h. Do I have to recursively redefine all of these types (by hand) in the Cython file before being able to use this library? Where would I write them?
Thanks!
UPDATE 6
Finally at the step of wrapping a function!
from libc.stdint cimport uint8_t

cdef extern from "<apriltag.h>":
    cdef struct apriltag_detection:
        int id
        double c[2]
        double p[4][2]

    ctypedef apriltag_detection apriltag_detection_t

cdef extern from "tag36h11_detector/tag36h11_detector.h":
    apriltag_detection_t* scan_frame(int width, int height, uint8_t* data);

def detect(width, height, frame):
    return scan_frame(width, height, frame)

tag36h11_detector.pyx:15:21: Cannot convert 'apriltag_detection_t *' to Python object

apriltag_detection_t* is meant to be an array of structs
UPDATE 5
This seems to have worked.
from libc.stdint cimport uint8_t

cdef extern from "<apriltag.h>":
    cdef struct apriltag_detection:
        int id
        double c[2]
        double p[4][2]

    ctypedef apriltag_detection apriltag_detection_t

cdef extern from "tag36h11_detector/tag36h11_detector.h":
    apriltag_detection_t* scan_frame(int width, int height, uint8_t* data);

UPDATE 4
Solved the previous issues by importing the necessary types.
from libc.stdint cimport uint8_t

cdef extern from "apriltag.h":
    cdef struct apriltag_detection:
        int id
        double c[2]
        double p[4][2]

    ctypedef apriltag_detection apriltag_detection_t

cdef extern from "tag36h11_detector.h":
    apriltag_detection_t* scan_frame(int width, int height, uint8_t* data);

tag36h11_detector.c:533:10: fatal error: 'apriltag.h' file not found

I'm not sure where this is coming from because my header file, as provided in the original post, required <apriltag.h> and not "apriltag.h". This is what my setup.py looks like.
from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(ext_modules=cythonize(Extension(\
    name='tag36h11_detector', \
    sources=["tag36h11_detector.pyx", \
    "tag36h11_detector/tag36h11_detector.c"], \
    include_path=["/usr/local/include/apriltag"], \
    libraries=["apriltag"])))

UPDATE 3
cdef extern from "apriltag.h":
    cdef struct apriltag_detection:
        int id
        double c[2]
        double p[4][2]

    ctypedef apriltag_detection apriltag_detection_t

cdef extern from "tag36h11_detector.h":
    apriltag_detection_t* scan_frame(int width, int height, uint8_t* data);

tag36h11_detector.pyx:10:60: 'uint8_t' is not a type identifier

UPDATE 2
This is my current code and the following is the compilation error
// tag36h11_detector.pyx
cdef extern from "apriltag.h":
    ctypedef apriltag_detection_t:
        int id
        double c[2]
        double p[4][2]

cdef extern from "tag36h11_detector.h":
    apriltag_detection_t* scan_frame(int width, int height, uint8_t* data);

// apriltag.h
    ...
    typedef struct apriltag_detector apriltag_detector_t;
    ...

tag36h11_detector.pyx:2:33: Syntax error in ctypedef statement

UPDATE 1
So I'm trying to interface with the above header file with Python (which I wrote and implemented) with types defined in apriltag.h (from a library).
cdef extern from "apriltag.h":
    struct apriltag_detection:
        int id
        double c[2]
        double p[4][2]

cdef extern from "tag36h11_detector.h":
    struct apriltag_detection* scan_frame(int width, int height, uint8_t* data);

When I try compiling the above, I get

tag36h11_detector.pyx:8:29: Syntax error in struct or union definition

A: This is basically covered in this part of cython documentation, which says that you only need to import parts, which you will be using in your cython code.
For example let's take a look at the following C interface:
#struct.h
struct Needed{
  int a;
};

struct NotNeeded{
  int b;
};

struct Combined{
  struct Needed needed;
  struct NotNeeded notneeded;
};

struct Combined create(void);

You would like to call the function create and use the value a from the Needed struct, that means you have to import struct Needed and parts of struct Combined but not NotNeeded in your cython code:
#struct_import.pyx
cdef extern from "struct.h":
     struct Needed:   # use "ctypedef struct Needed" if defined with typedef in h-file!
            int a
     struct Combined:  #NotNeeded is missing!
          Needed needed
     Combined create()

def get_needed():
    return create().needed.a #should be 42!

Now, using setup.py (its content can be seen further below, the same goes for the content of struct.cto) we get the expected result:
[] python setup.py build_ext --inplace
[] python -c "python -c "import struct_import as si; print si.get_needed()"
    42

If you use cython to glue some C code together, it is possible, even less is necessary. In oour example, if we had a C-function which would extract the needed value from the Combined struct:
#struct.h
...
int extract(struct Combined combined);//returns combined.needed.a

We could use it as follows in the pyx-file:
#struct_import.pyx
cdef extern from "struct.h":
     struct Combined:
          pass  #nothing imported!
     Combined create()
     int extract(Combined combined)

def get_needed():
    return extract(create()) #should be 42!

And despite we didn't import the Needed struct at all, it works as good as the first version.
So if it becomes a chore to import all those structs, one could extend the c interface to make it unnecessary.

To make the example complete, here the missing setup.py and struct.c files:
#setup.py:
from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(ext_modules=cythonize(Extension(
            name='struct_import',
            sources = ["struct_import.pyx", "struct.c"]
    )))

and
//struct.c
#include "struct.h"

struct Combined create(){
  struct Combined res;
  res.needed.a=42;
  res.notneeded.b=21;
  return res;
}

int extract(struct Combined combined){
   return combined.needed.a;
}


text:
Q: Can a Firefox add-on listen on a UNIX socket? I know how to listen on a dedicated port using nsISocketTransportService in Add-on sdk. But, is it possible to use UNIX socket in Add-on SDK to communicate with oher applications.

A: It seems you can't: https://support.mozilla.org/en-US/kb/permission-request-messages-firefox-extensions)
This would make sense, since:

*

*UNIX sockets are a special file on *nix

*they are not available across platforms

*this would be a huge security issue.

If you need to communicate with other software on the computer you can probably safely use regular network sockets, websockets, etc...


text:
Q: When a timerfd (set in user space) expires, execute a piece of user-defined code in the Linux kernel I have set a timerfd in the user space, when it expires, I would like the kernel to execute a piece of code I added.  Anyone can give me some suggestions?
Some ideas I have: accordding to the definition of *timerfd_setup* in file /fs/timerfd.c, the function *timerfd_tmrproc* is called. Can I add my codes inside the function *timerfd_tmrproc* ? My codes concern reset one self-defined variable (in sched_entity) as zero, so I also need to pass the tid of the thread to the function *timerfd_tmrproc*. Will it cause any risk to the system?
static int timerfd_setup(struct timerfd_ctx *ctx, int flags,
             const struct itimerspec *ktmr)
{
    enum hrtimer_mode htmode;
    ktime_t texp;
    int clockid = ctx->clockid;

    htmode = (flags & TFD_TIMER_ABSTIME) ?
        HRTIMER_MODE_ABS: HRTIMER_MODE_REL;

    texp = timespec_to_ktime(ktmr->it_value);
    ctx->expired = 0;
    ctx->ticks = 0;
    ctx->tintv = timespec_to_ktime(ktmr->it_interval);
    hrtimer_init(&ctx->tmr, clockid, htmode);
    ***hrtimer_set_expires(&ctx->tmr, texp);
    ctx->tmr.function = timerfd_tmrproc;***
    if (texp.tv64 != 0) {
        hrtimer_start(&ctx->tmr, texp, htmode);
        if (timerfd_canceled(ctx))
            return -ECANCELED;
    }
    return 0;
}


text:
Q: How to show month and year only in 720kb AngularJS Datepicker I'm using this angularJS datepicker in my application and would like to know if there is a way to display only months and years in the calendar and remove the days?
This is how I'm using the datepicker:
<datepicker date-format="MM yy" button-prev-title="previous month" button-next-title="next month" button-prev="" button-next="" id="dtDate" name="dtDate" >
    <input ng-model="dtDate" />
</datepicker>

I tried to add date-format="MM yy" but it only changes the selected date and not the datepicker itself.

A: I think you might be interested in using this git repository that I created.
https://github.com/morfsys/multiple-month-picker
This is how you can use it in your project:
HTML
<input type="text" multiple-month-picker />

JS
//Initiate your app by injecting 'mmp-morfsys'
var app = angular.module('app-name', ['mmp-morfsys'])

It helps you to select multiple months across multiple years. The best thing? It is on AngularJS.
I hope it helps you.

A: I have the same problem with angularjs-datepicker.
I used another datepicker: angularjs-material.
Here is how you can use it:
<md-datepicker ng-model="startDate" md-mode="month" md-placeholder="dd/MM/yyyy" md-date-locale="mylocale" md-open-on-focus></md-datepicker>

And then in your controller:
function pad(n) {return n < 10 ? "0"+n : n;}
$scope.mylocale = {
  formatDate: function(date) {
    var d=new Date(date);
     if(isNaN(d.getTime())) {
       return '';
     } else {
       return pad(d.getDate())+"/"+pad(d.getMonth()+1)+"/"+d.getFullYear();
     }
  },
  parseDate: function(date) {
     var ds = date.split('/');
     var d=new Date(ds[2],ds[1]-1,ds[0]);
     if(isNaN(d.getTime())&&d!=''){
       return new Date(NaN);
      } else {
        return d;
      }
   } };

And it is working. Just make sure that you properly handle case when input is invalid (form.startDate.$invalid).
If someone has a solution for angularjs-datepicker, please let us know.


text:
Q: How to set indent only return key with php-mode in emacs I installed php-mode from https://github.com/ejmr/php-mode.
With this mode I need to hit TAB to make indentation like this.
if (conditon){ # Hit `return`
| <- cursor stays here.
}

if (conditon){ # Hit `return`
    | <- I want to set cursor hier without hitting `TAB`.
}

I think if I re-define key bind for RET then cursor moves as I expected, but I don't know how to write it. Can somebody help me?

A: You want to enable electric-indent-mode.

A: The function you want, newline-and-indent, is by default bound to C-j instead of RET.
So you could either just start using C-j (which I did because I found those keys actually easier to access than RET), or redefine RET with either the define-key line from the other answer, or alternatively a local-set-key in the php-mode-hook like this:
(defun set-ret-to-newline-and-indent ()
  (local-set-key (kbd "RET") 'newline-and-indent))
(add-hook 'php-mode-hook 'set-ret-to-newline-and-indent)

A: Try something like this:
(eval-after-load "php-mode"
  '(define-key php-mode-map (kbd "RET") 'newline-and-indent))


text:
Q: Change appearance rows in WPF ListView c# window In my windows application I defined a window with a list. There are items in this list based on the binder (for the moment I put in the items programmatically).
<ListView x:Name="event_list" IsEnabled="False">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Path=Type}"/>
            <GridViewColumn Header="Description" DisplayMemberBinding="{Binding Path=Description}"/>
        </GridView>
    </ListView.View>
</ListView>

var row = new { Type = "type", Description = "description" };
event_list.Items.Add(row);

Lets say I want to change the 3rd row and make the font weight bold, how do I achieve this?
Clearly, the following doesn't compile:
event_lits.Items[2].FontWeight = FontWeights.Bold;

Because the Items propperty returns only the strings I put in, not the view object of the row itself.
Notes for eager answerers:
 In a wpf window, a ListView is this class, not this class (the reason why 9/10 google searches on this topic fails).

A: You could add an ItemContainerStyle with a DataTrigger that binds to a property of the data object:
<ListView x:Name="event_list" IsEnabled="False">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsBold}" Value="True">
                    <Setter Property="FontWeight" Value="Bold" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Path=Type}"/>
            <GridViewColumn Header="Description" DisplayMemberBinding="{Binding Path=Description}"/>
        </GridView>
    </ListView.View>
</ListView>

Sample data:
event_list.Items.Add(new { Type = "type", Description = "description" });
event_list.Items.Add(new { Type = "type", Description = "description" });
event_list.Items.Add(new { Type = "type", Description = "description", IsBold = true });
event_list.Items.Add(new { Type = "type", Description = "description" });

In WPF you are generally not supposed to set properties of the visual containers in the code-behind.


text:
Q: (J2me) Stream as a buffer? Here I got a j2me application and I need to transmit or save live data from a output stream.
What could happen if I use one thread to write data to the stream and after writing certain no ofl bytes other thread to get a bytearray out of it save or transmit it and reset the stream to zero..
I.e calling reset on it .. This effectively equals to using stream as fixed size buffer..
The constrain here is that I may not be able to use the byteBuffer object for the purpose
will that make the stream invalid because the first thread is still wiring to it?

A: I assume that you are going to use java.io.ByteArrayOutputStream class, which is part of CLDC 1.0 standard of J2ME.
CLDC 1.0 does not say anything about thread safety of ByteArrayOutputStream.
But if you look implementation of ByteArrayOutputStream, all needed methods seems to be synchronized:
public synchronized byte toByteArray()[] { ... }
public synchronized void reset() { ... }
public synchronized void write(byte b[], int off, int len) { ... }

If you have access to sources of your J2ME classes. You can double check that.
If methods are synchronized, then it should be safe to use stream as you plan.


text:
Q: Has CodeIgniter 2.0 / PHPUnit happened yet? So i've just had a pretty disappointing morning/weekend. It came in the form of setting up PHPUnit, Integrating Eclipse etc
Now i've just discovered that there's no straightforward way to test CodeIgniter 2.0 applications directly from PHPUnit.
I've spent a lot of time researching libraries (FooStack and CIUnit) but the development of these has ceased and aren't compatible with CI 2.0
Before I jump in the inlcuded 2.0 Unit Testing class I need to ask, have I missed out on any major developments around CI 2.0 and PHPUnit.
Any guidance greatly appreciated.
Thanks,
Conor

A: I found a few resources you may find useful.
A class written to integrate PHPunit and Codeigniter. Not a very interesting forum post, but it lead me to the next link.
http://codeigniter.com/forums/viewthread/70934/P60
However, the repository found in the link above doesn't look very active. This fork of it seems to be a little more active:
https://bitbucket.org/kenjis/my-ciunit

A: A quick note to anybody interested in this. Ellis Labs are currently baking support for PHPUnit in CodeIgniter Reactor. The next release should have it.. Ref: ellislab.com/forums/viewthread/187601


text:
Q: How to instantiate class with nested abstract field with Jackson? I've got following classes :
public class City
{
    Zoo zoo;
}

public class Zoo
{
    Animal[] animals;
}

public abstract class Animal
{
    String name;

    abstract void eat();
}

I want to deserialize an instance of City class with Jackson. Howerer, since Animal is an abstract type, I've got following exception:

Could not read JSON: Can not construct instance of Animal, problem:
  abstract types either need to be mapped to concrete types, have custom
  deserializer, or be instantiated with additional type information

How to map Animal to concrete type?
The problem is that I am able to modify only City class.

A: Since you can modify only the City class, you may find mix-in annotations useful. The idea is you create and annotate a a new class that acts as a surrogate for the class you wish you could annotate (but can't for whatever reason). Then you register your surrogate with Jackson, telling it to look for annotations on your surrogate instead of the actual class.
To start with, you could try creating a mix-in for Animal and annotating the mix-in class with @JsonDeserialize(as=ConcreteClass.class) as Vince Emigh suggested. Once you've got that working, you can try annotating it with polymorphic type handling annotations.

A: For one-to-one (abstract/impl) use case, registering sub-classes (which you can do via ObjectMapper.registerSubtypes(...), or using SimpleModule) is an alternative to annotations.
But if you have truly polymorphic type, @JsonTypeInfo annotation is the key. It needs to be added in the base class that is used static type (like Animal), and will result in addition of a Type Identifier on serialization, and use of that id on deserialization.
There are multiple choices both for kind of type id (class name vs logical name) as well as inclusion style (as property, as wrapper array, as wrapper object, as external property).


text:
Q: How to join hive tables based on condition of the joining column We have a hive table like below:
num    value

123     A
456     B
789     C
101     D

The joining table is:
num       Symbols

123         ASC
456001      JEN
456002      JEN
456003      JEN
789001      CON
101         URB

Our expected result:
num   value   symbols
123    A       ASC
456    B       JEN
789    C       CON
101    D       URB

Currently we are joining the tables twice in order to get the results.
Like first time insert into some tmp table using the below query:
select
a.num,
a.value,
b.symbols
from mytable a
join mytable b on a.num = b.num;

This query is producing the results for keys 123,101.
Next, we are running another query like below:
select
    a.num,
    a.value,
    b.symbols
    from mytable a
    join mytable b on CONCAT(a.num,'001') = b.num;

This query is producing the results for keys 456, 789.
These two queries results are inserted into some tmp hive table and we select the final results from the tmp table.
This looks a bad design overall. but I would like to know if there is a better way to achieve this. Thanks.
Query Result
for
Select
    a.num
    ,a.value
    ,b.symbols
    from
    (select substr(num,3) as num, value from table)a
    join
    (select substr(num,3) as num, symbols from table) b
    on a.num = b.num

a.num   a.value b.symbols
3        A      ASC
1        D      URB

A: OK, just one sql can implement your requirement.see below, table a is the table with value column and table b is the table with the symbols column, the SQL:
select
    distinct a.num,
    a.value,
    b.symbols
from
    mytable1 a
join
    mytable2 b on substr(cast(b.num as string),0,3) = cast(a.num as string)

A: If datatype of num is String then you can try with Substr
Select
a.num
,a.value
,b.symbols
from a join b on
substr(a.num,3) = substr(b.num,3)

A: Can you pls try this
Select
    a.num
    ,a.value
    ,b.symbols
    from
    (select substr(num,3) as num, value from table)a
    join
    (select substr(num,3) as num, symbols from table) b
    on a.num = b.num

A: Can you try with left semi join with above query as shown below.
    Select
    a.num,
    a.value,
    b.symbols
from
    mytable1 a
    Left semi join
    mytable2 b on substr(cast(b.num as string),0,3) = cast(a.num as string)


text:
Q: Remove previews from dropzone after success without page refresh I have a page where the dropzone uploaded is called inside a modal. The modal is called depending on the different preview parameters passed from a list. After the file is uploaded the preview of the dropzone div needs to be cleared on modal dismiss without page refresh.

A: The above is attained by adding the following two lines in the button click event inside the jquery code block:
<script type="text/javascript">
 $(function () {
        $("#SaveAndEmail").click(function (e) {
            e.preventDefault();
            ///Add your code for saving
            $('.dz-preview').empty();
            $('.dz-message').show();
        });
    });
</script>


text:
Q: how to style only a part of text in css I need to add superscript in dropdownlist options. I tried many ways but nothing worked out.
So help me to how to style a only a part of option text to make it appear like superscript.
please help me,also if you know any other way to add superscript in dropdownlist options. thanks

A: There is no way to do this in HTML/CSS/Javascript
However for all those trying to do it out of a <select> tag, wrap the content you intend to superscript in a  element and then apply CSS to it.
Example
HTML

x2 = 9

CSS
span.superscript { vertical-align: super; font-size:50%; }

Fiddle demo


text:
Q: Links with caret ^ do not work? See my answer to a question on programmers.stackexchange.com. I used the markup to link to a website. Is there a reason why this isn't working? The text is not hyperlinked properly.

A: The problem has to do with the carets in the URLs. I removed the carets and the text became a link immediately. It's a bug alright, +1.
EDIT:
Turns out this is not a bug in the strictest sense of the term; see what Jeff and Nick have to say.
Your source:

Have you considered using [LoadRunner][1]? When I worked on Government projects,
we used [LoadRunner][2] to baseline builds and determine their performance.
It works really well.

  [1]: http://[snip].jsp?zn=bto&cp=1-11-126-17^8_4000_100
  [2]: https://[snip].jsp?zn=bto&cp=1-11-126-17^8_4000_100

Deleting the carets produces this (which doesn't link to the right places, obviously):
Have you considered using LoadRunner? When I worked on Government projects, we used LoadRunner to baseline builds and determine their performance. It works really well.

A: As of recently, when entering a link via the button (or Ctrl-L), these "evil" characters will automatically be escaped.

A: http://drupal.org/node/353579

The caret ("^") is NOT a valid URL character and must be percent encoded if you follow the recommendations of the IETF. This is one of the "unsafe" characters defined in RFC1738 (which was updated by RFC3986).

RFC1738: 2.2 URL Character Encoding Issues
    ...
    Unsafe:
Characters can be unsafe for a number of reasons. The space
    character is unsafe because significant spaces may disappear and
    insignificant spaces may be introduced when URLs are transcribed or
    typeset or subjected to the treatment of word-processing programs.
    The characters "<" and ">" are unsafe because they are used as the
    delimiters around URLs in free text; the quote mark (""") is used to
    delimit URLs in some systems. The character "#" is unsafe and should
    always be encoded because it is used in World Wide Web and in other
    systems to delimit a URL from a fragment/anchor identifier that might
    follow it. The character "%" is unsafe because it is used for
    encodings of other characters. Other characters are unsafe because
    gateways and other transport agents are known to sometimes modify
    such characters. These characters are "{", "}", "|", "\", "^", "~",
    "[", "]", and "`".
All unsafe characters must always be encoded within a URL.
    ...

RFC3986 updated RFC1738 to allow the tilde character ("~") to be used, (and the "#" character is the reserved delimiter for the fragment portion of the URI), but the "^" char is still a no-no to use unencoded if you wish to adhere to the IETF recommendations. That said, yes, some people do not follow the recommended procedures and use the caret, unencoded (in the query portion of the URI), but this is still a mangling of the standard and certainly should not be encouraged IMHO.

Caret ^ is not a valid URL character.


text:
Q: which in a way they had Right down the long, broad, straight highway through Altona towards the centre of Hamburg other drivers had heard the same broadcast and were pulling in to the other side of the roads as if driving and listening to the radio had suddenly become mutually exclusive, which in a way they had.
Source: Frederick Forsyth: The Odessa File. Corgi Books: London, 1980, p. 12.
Can you please clarify to me the bolded part which does not make much sense to me. The translator of the novel to my native language this passage translates in a sense as: and that was true or that was the case.

A: The meaning of "which in a way they had" in the quoted passage is that "driving" and "listening to the radio" had in fact become exclusive in a way, that the drivers could not do both at the same time. This contrasts with the "as if" earlier in the passage. The "as if" says that these two actions were not in fact mutually exclusive, but drivers acted as if they were. but then "which in a way they had" says that in some sense they had become exclusive after all.
The translation of this to "and that was true" catches much of the sense, although not the nuance, of this phrase.
For context, The "broadcast" mentioned in the passage was an announcement of the death of US President Kennedy. Presumably drivers found it impossible to continue driving as they listened to and comprehended this very shocking and distressing news.


text:
Q: Separate [Advanced Custom Field] values by commas I have a 'relationship' custom field that allows you to select multiple values and display them via
<?php $post_objects = get_field('field');
   if($post_objects!=''){ ?>
   <?php foreach( $post_objects as $post): ?>
   <?php setup_postdata($post); ?>
       <a href="<?php the_permalink(); ?>">
           <?php the_title(); ?>,

   <?php endforeach; ?>
<?php wp_reset_postdata(); ?>

This works for now but is not very pretty as it returns the values as "Value, Value, Value,".
What I would like it to output is...

1 Value = "Value"
2 Values = "Value & Value"
3 or more Values = "Value, Value & Value"

"

A: Try to grab the output and echo together.
<?php $post_objects = get_field('field');
   if($post_objects!='') :
   $value = array(); ?>
   <?php foreach( $post_objects as $post): ?>
       <?php setup_postdata($post); ?>
       <?php $values[] = ''. the_title('','',false) .''; ?>
   <?php endforeach; ?>
   <?php endif; ?>
<?php wp_reset_postdata(); ?>

<?php echo join( ', ', $values); ?>

A: You can use the number_format function of PHP.
You will get something like 2,500

  <?php if (get_field('events_price_yen')) { ?>

        <?php $english_format_number = number_format(get_field('events_price_yen'));
              echo $english_format_number; ?>

  <?php }; ?>


text:
Q: 2 SetTimeOut Method inside Promise not working Couldn't find a solution for the same hence reaching out to you guys for help.
I have 2 JS method that needs to be called a specific time interval continuously so to achieve this i used SetTimeout as shown below but it does not seem to work and only second setTimeout is called . Ideally i expected that both methods would be called after the mentioned time.
My code:-
var statusPromise = new Promise(function(resolve, reject) {
    setTimeout(function() {
        plugin.dcsHelper.getMeterStatus(function(data) {
            plugin.dcsHelper.log("INFO", "Status: " + JSON.stringify(data));
            if (data && data.status) {
                resolve(data.status);
            }
        }, function(err) {
            plugin.dcsHelper.log("ERROR", "Error while polling: " + JSON.stringify(err));
        });
    }, 1000);
});

var progressPromise = new Promise(function(resolve, reject) {
    setTimeout(function() {
        plugin.dcsHelper.getProgress2(function(data) {
            plugin.dcsHelper.log("INFO", "Value: " + JSON.stringify(data));
            if (data && data.val) {
                resolve(data.val);
            }
        }, function(err) {
            plugin.dcsHelper.log("ERROR", "Error while polling: " + JSON.stringify(err));
        });
    }, 5000);
});

Promise.all([statusPromise, progressPromise]).then(function(values) {
    console.log(values);
});

Here the method inside progressPromise is only getting called and the method inside statusPromise is not getting called.
Any help will be much appreciated.!!

A: Actually the above code is completely right and promise works as expected . The problem was with the Plugin java code which i was using.


text:
Q: IOS COREBLUETOOTH:convert characterstic.value Doing corebluetooth app and able to read and write values when i am getting values in did update value for charactersticI can see that i have received proper response from peripheral as 01117100352e36302e313100000000e55a
     01 - 01-start byte
     11 - 17(Dec) - length of responce packet
     71 - response ID
      00 - Ignore this byte
   So now out of total length 17, first 4 bytes are header, last 2 bytes are CRC. We
 need to read remaining 11 bytes and convert them to ASCII.
35 - 5
2e - .
36 - 6
30 - 0
2e - .
31 - 1
31 - 1
So Iam getting version number from watch as 5.60.11

i have tried with the "IOS:Convert hex values from the characterstic.value result" link i am getting  the value as above but when applying same code  for010c5700010159105a105381  i need to get 100% and what i am getting in console is 00 .I had many values like that every value should be converted as above and show can any on help.


text:
Q: SimpleXML Parsing Nested Namespaces - PHP I am having a small problem parsing the tags in the nested namespace called "q0:", located below.
//Tag that I am trying to parse
  <q0:CustomerTransactionId>

I am able to get to all of the "v12:" namespaced tags but not the "q0:" ones for some reason.
Thanks!
Here is the XML
<?xml version="1.0" encoding="UTF-8"?>
 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
 <env:Header
       xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<soapenv:Body>
<v12:ProcessShipmentReply
    xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:v12="http://fedex.com/ws/ship/v12">
    <v12:HighestSeverity>ERROR</v12:HighestSeverity>
    <v12:Notifications>
        <v12:Severity>ERROR</v12:Severity>
        <v12:Source>ship</v12:Source>
        <v12:Code>3058</v12:Code>
        <v12:Message>Recipient Postal code or routing code is required</v12:Message>
        <v12:LocalizedMessage>Recipient Postal code or routing code is required</v12:LocalizedMessage>
    </v12:Notifications>
    <q0:TransactionDetail xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:q0="http://fedex.com/ws/ship/v12">
        <q0:CustomerTransactionId>21445634</q0:CustomerTransactionId>
    </q0:TransactionDetail><q0:Version xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:q0="http://fedex.com/ws/ship/v12">
    <q0:ServiceId>ship</q0:ServiceId>
    <q0:Major>12</q0:Major>
    <q0:Intermediate>0</q0:Intermediate>
    <q0:Minor>0</q0:Minor>
  </q0:Version>
  </v12:ProcessShipmentReply>
  </soapenv:Body>
  </soapenv:Envelope>

And here is my parse
    $xml = simplexml_load_string($result, NULL, NULL, 'http://schemas.xmlsoap.org/soap/envelope/');
    $xml->registerXPathNamespace('env', 'http://schemas.xmlsoap.org/soap/envelope/');
    $xml->registerXPathNamespace('v12', 'http://fedex.com/ws/ship/v12');
    $xml->registerXPathNamespace('q0', 'http://fedex.com/ws/ship/v12');

    $bodies = $xml->xpath('env:Body');

    foreach($bodies as $body){

        $reply = $body->children('v12', TRUE)->ProcessShipmentReply;
        $reply2 = $body->children('q0', TRUE)->TransactionDetail;

        $custInfoArr['status'] = (string) $reply->HighestSeverity;

        if(strtolower($custInfoArr['status'])=="error"){

            $custInfoArr['invoiceNum'] = (string)$reply2->CustomerTransactionId;
            $custInfoArr['notificationSeverity']= (string) $reply->Notifications->Severity;
            $custInfoArr['notificationSource']= (string) $reply->Notifications->Source;
            $custInfoArr['notificationCode']= (string) $reply->Notifications->Code;
            $custInfoArr['notificationMessage']= (string) $reply->Notifications->Message;
            $custInfoArr['notificationLocalizedMessage']= (string) $reply->Notifications->LocalizedMessage;

        }

        $custInfoArr['trackingCode'] = (string) $reply->CompletedShipmentDetail->CompletedPackageDetails->TrackingIds->TrackingNumber;
        $custInfoArr['labelCode'] = (string) $reply->CompletedShipmentDetail->CompletedPackageDetails->Label->Parts->Image;
        $custInfoArr['labelCode'] = base64_decode($custInfoArr['labelCode']);

    }

A: <q0:TransactionDetail> is not a child of <env:Body>, it is a child of <v12:ProcessShipmentReply>, so you need to look for it inside $reply, not $body: $reply2 = $reply->children('q0', TRUE)->TransactionDetail;
The important thing to remember is that both the ->TagName operator and the ->children() method only look at immediate children of a particular node, they are not doing a "deep search" like XPath.
In fact, looking, both v12: and q0: are aliases for the same namespace ('http://fedex.com/ws/ship/v12'), so the next line can just be $reply2 = $reply->TransactionDetail. If you just say $reply = $body->children('http://fedex.com/ws/ship/v12')->ProcessShipmentReply rather than relying on the alias, this becomes clearer (and safer, since those aliases may change).
Incidentally, unless you're using it for something else, you can also get rid of all your XPath code (including all of the registerXPathNamespace calls) and just write $body = $xml->children('http://schemas.xmlsoap.org/soap/envelope/')->Body (I'm pretty sure SOAP only allows one Body per message).


text:
Q: Create Row with Equal Height Column of Image and Column of Scrollable List Group Does anyone know how to create two responsive Bootstrap 4 columns with the same height where one column is an image and the other is a scrollable list?
Here's a fiddle (note that I don't want the list group to exceed the height of the image as the viewport is resized): https://jsfiddle.net/lgants/gyk31vow/
I've literally spent days on this so any help would be greatly appreciated!
HTML:

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Porta ac consectetur ac

Porta ac consectetur ac

Porta ac consectetur ac

Porta ac consectetur ac

CSS:
img {
  max-width:100%;
  max-height:100%;
  object-fit: contain;
}

.list-group {
  overflow-y: scroll;
}

A: So what you need to do in this case is use JS to find the height of the image and set the height of the list equal to the height of the image. Also since Bootstrap 4 uses flex display on rows you need to set the cols to align-items: start; by giving the row a class of align-items-start I'm using Bootstrap v4-beta

var picHeight = $('.pic-height').height();
$('.list-group').css('height', picHeight);

$(window).resize(function() {
 var picHeight = $('.pic-height').height();
 $('.list-group').css('height', picHeight);
});
img {
  max-width:100%;
  max-height:100%;
  object-fit: contain;
}

.list-group {
  overflow-y: scroll;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Porta ac consectetur ac

Porta ac consectetur ac

Porta ac consectetur ac

Porta ac consectetur ac

Porta ac consectetur ac

Porta ac consectetur ac

Porta ac consectetur ac

Porta ac consectetur ac


text:
Q: Error received when passing in &mreq argument into setsockopt method I want to add a socket to a group which receives data from the network host. The page http://www.tldp.org/HOWTO/Multicast-HOWTO-6.html explain clearly well how the socket option IP_ADD_MEMBERSHIP and the ip_mreq data structure are used to acquire this. So I create my ip_mreq data structure(I call my instance mreq) and fill in both of its properties imr_multiaddr and imr_interface, but when I pass the value &mreq into the optval parameter, I get the error:
Error: Argument of type 'ip_mreq *' is incompatible with parameter of type 'const char *'
But why does that parameter require 'const char *', when the guide I'm following states that the parameter should be of type 'cont void *'. Before this issue I had a problem with the ip_mreq data structure not being defined, but I solved that by importing the Ws2ipdef header library. I think the issue may be that I imported the wrong library or I may need to import an additional library.
Also I am coding my solution in C++ using visual basics.
Thank you

A:
But why does that parameter require 'const char *', when the guide I'm following states that the parameter should be of type 'cont void *'

Because setsockopt() is used for dozens of socket options besides IP_ADD_MEMBERSHIP.
You have to cast.
NB Arbitrary Internet resources are not normative references.


text:
Q: Excel - Split cell with a delimiter and if delimiter not found get complete cell value to another cell I have an excel file with data where I want a Split cell with a delimiter and if the delimiter is not found then copy that cell value to another cell
e.g.
ABC Ltd.
ABC Ltd. - Ind
PQR Ltd. - USA
LMN Corp.
Output - delimiter "-"
ColumnA       ColumnB
ABC Ltd.   ABC Ltd.
ABC Ltd.    Ind
PQR Ltd.     USA
LMN Corp.    LMN Corp.
However, I'm using below formula but not getting what I want.
=TRIM(LEFT(B2,FIND("-",B2)-1))
=TRIM(REPLACE(B2,1,FIND("-",B2),""))

A: You need to put in error handling for the case where B2 doesn't contain a '-'
=IFERROR(TRIM(LEFT(B2,FIND("-",B2)-1)),TRIM(B2))

and
=IFERROR(TRIM(REPLACE(B2,1,FIND("-",B2),"")),TRIM(B2))

A: Another solution:

Formula:
=IF(LEN(A1)-LEN(SUBSTITUTE(A1,"-",""))>0,RIGHT(A1,LEN(A1)-FIND("-",A1,1)-1),A1)

A: Alternative approach (doesn't necessarily mean better though ;) )
1
=TRIM(LEFT(B2&"-",FIND("-",B2&"-",1)-1))

2
=TRIM(RIGHT(SUBSTITUTE(A2,"-",REPT(" ",99)),99))


text:
Q: Loading external html using jquery.load() function gives unexpected results I had a previous post related to this problem but I guess I was not clear enough or some other reason, I did not get a solution.
Old post here
I now have minimized the whole html to just demonstrate the problem and uploaded the html.
Here the link to the loaded HTML
There are two html files - main.html and sample.html. Main.html loads sample.html using jQuery.load(). There is a JavaScript inside the sample.html which query the width of a div and visibility of a div. Both queries gives wrong results. You can look at the debug console of the browser for the results returned. I have tried FF, IE and chrome and all gives the consistent wrong values. I guess I am not doing something correctly. What could be wrong here ?


text:
Q: How to check the phone is locked in android? How to check the phone is locked or not in android?

A: I attached the answer for finding the phone is locked or not,
i declared the code below,
KeyguardManager km = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
boolean locked = km.inKeyguardRestrictedInputMode();
if(locked == true){
  // do something
}else{
  // do something else
}


text:
Q: Is it ok to send to token from frontend to backend? If I have an application in which a user can connect to facebook from the frontend, it is ok to send the access token to the backend?
If there are security risks, what are them?

A: Yes, it is ok.
You only should verify your token on backend. Facebook has special endpoint for that - https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#checktoken

A: As a matter of fact, you can send the long lived access tokens to the server so that you don't have to ask the user to authenticate with Facebook every time.
The concern is to keep the database encrypted at rest in the server so that the tokens are not compromised. Also consider sending it only to servers with https so that the data is not sent in plaintext from client


text:
Q: Overwrite file but still read content I'm trying to find the most reasonable way to open a file, modify its content and then write it back to file.
If I have the following "MyFile.xml"
<?xml version="1.0" encoding="utf-8"?>
<node>
  <data>this is my data which is long</data>
</node>

And then want to modify it according to this:
private static void Main(string[] args)
{
    using (FileStream stream = new FileStream("Myfile.xml", FileMode.Open))
    {
        XDocument doc = XDocument.Load(stream);
        doc.Descendants("data").First().Value = "less data";
        stream.Position = 0;
        doc.Save(stream);
    }
}

I get the following result. Note that, since the total file length is less than before I get incorrect data at the ending.
<?xml version="1.0" encoding="utf-8"?>
<node>
  <data>less data</data>
</node>/node>

I guess I could use File.ReadAll* and File.WriteAll* but that would mean two File openings. Isn't there some way to say "I want to open this file, read its data and when I save delete the old content" without closing and reopening the file? Other solutions that I have found include FileMode.Truncate, but that would imply that I cannot read the content.

A: You'll have to use FileStream.SetLength like this:
stream.SetLength(stream.Position);

After you have finished writing.
Of course, assuming that the position is at the end of the written data.

A: Why do you read the file into a filestream first?
You can do the following:
private static void Main(string[] args]
{
   string path = "MyFile.xml";
   XDocument doc = XDocument.Load(path);
   // Check if the root-Node is not null and other validation-stuff
   doc.Descendants("data").First().Value = "less data";
   doc.Save(path);
}

The problem with the stream is, that you can either read or write.
I've read, that with the .net-Framework 4.5 it's also possible to read and write on a stream, but haven't tried it yet.


text:
Q: Compressing and copying large files on Windows Server? I've been having a hard time copying large database backups from the database server to a test box at another site. I'm open to any ideas that would help me get this database moved without having to resort to a USB hard drive and the mail.
The database server is running Windows Server 2003 R2 Enterprise, 16 GB of RAM and two quad-core 3.0 GHz Xeon X5450s. Files are SQL Server 2005 backup files between 100 GB and 250 GB.
The pipe is not the fastest and SQL Server backup files typically compress down to 10-40% of the original, so it made sense to me to compress the files first. I've tried a number of methods, including:

*

*gzip 1.2.4 (UnxUtils) and 1.3.12 (GnuWin)

*bzip2 1.0.1 (UnxUtils) and 1.0.5 (Cygwin)

*WinRAR 3.90

*7-Zip 4.65 (7za.exe)

I've attempted to use WinRAR and 7-Zip options for splitting into multiple segments. 7za.exe has worked well for me for database backups on another server, which has ~50 GB backups.
I've also tried splitting the .BAK file first with various utilities and compressing the resulting segments. No joy with that approach either- no matter the tool I've tried, it ends up butting against the size of the file.
Especially frustrating is that I've transferred files of similar size on Unix boxes without problems using rsync+ssh. Installing an SSH server is not an option for the situation I'm in, unfortunately.
For example, this is how 7-Zip dies:
H:\dbatmp>7za.exe a -t7z -v250m -mx3 h:\dbatmp\zip\db-20100419_1228.7z h:\dbatmp\db-20100419_1228.bak

7-Zip (A) 4.65  Copyright (c) 1999-2009 Igor Pavlov  2009-02-03
Scanning

Creating archive h:\dbatmp\zip\db-20100419_1228.7z

Compressing  db-20100419_1228.bak

System error:
Unspecified error

A: qpress for fast compression with low cpu load, i used it for 130GB SQL 2008 backup dump. It compressed to 34GB file at ~35MiB/s which I think is impressive.

A: Could you use rsync, without the ssh? I don't see where encryption is a requirement, and rsync runs okay on Windows.
How about gzip through netcat? The file(s) should just go through, without running into the problems of the intermediate steps.
Just thinking out loud...sorry I don't have something definitive.

A: After having compressed the db, could you consider using robocopy to copy over the file?

A: If your utilities are choking on the size of the backup file, just make more backup files, each will be smaller. You can have the SQL Server backup command to use multiple files. Microsoft calls this a "striped" backup set. Here's a stupid example:
backup database foo to disk='c:\foo.01.bak', 'c:\foo.02.bak', 'c:\foo.03.bak'
You can specify as many files as you would care to. Full documentation on the backup command is here.
Alternatively, if you have some money to burn you can use CA's Lightspeed or a similar product. This is an install on the server, but it will compress all server backups. This will result in shorter backup times, which DBAs and sysadmins usually like. CA provides a distibutable command-line utility to decompress a backup that uses their format, so you can send the backup file to anywhere.

A: Well here e is what I did ;)

*

*Virtualization on both ends.

*Domain controller on both ends ;) Gives me an external DC backup.

*DFS replication for transfers ;) This one runs nicely in the background, uses compression and just keeps ticking.

A: When I need to bring our database down from the data centre to the office I just do the backup in MSSQL and then compress again with winrar. I bring a 4 gig DB backup down to about 500MB then I just use the FTP server to do the transfer. Even if it stops FileZilla will let you resume.
Takes about 15 minutes to download.

A: Try compressing using IZARC http://www.izarc.org/izarccl.html - which has a command line addon.
I had cases when compressing was not succesfull on large files (about 25GB in size) but managed using IZARC -although I used the gui version not the command line addon.

A: I'm testing this right now:

*

*SQL Dump to .bak files

*GZip with the rsyncable option

*rsync the gzip files.

RSync is probably the best even if you don't gzip it because it only dups the diff.
I'm using cygwin binaries and my batch has these helpful lines (as well as many others including emailing me the log):
:: Getting a list of backup files ".bak"
dir /b c:\temp\db_backups | findstr bak > c:\temp\db_backups\filelist.txt
:: For each line in the file list from above, gzip it rsyncable!
for /F %%i IN (c:\temp\db_backups\filelist.txt) DO c:\cygwin\bin\gzip -9 --rsyncable -v -q c:\temp\db_backups\%%i

:: rsync it to a UNC path on a server
:: if you want to ssh it or ftp it you'd need to tweak the transport method
:: but I'm just using a UNC path.

c:\cygwin\bin\rsync --remove-source-files -Prv --delete --force --stats --itemize-changes --log-file=c:\temp\daily.backup.rsync.log "/cygdrive/c/temp/db_backups" "//unc/path/to/my/server/e$/dbs"

Usually you represent UNC paths as \unc\path\to\my\server...etc but cygwin and rsync no likey the other way.
You can also use rsync over ssh.
rsync -PavzrH -e "ssh" --delete --force --stats --itemize-changes --log-file=/cygdrive/c/temp/rsync_offsite_bkp.log /cygdrive/c/temp/db_backups your_user@yoursshserverhost.com:/mnt/data/share/stuff

the "/mnt/data/share/stuff" is the target directory where all your stuff gets stored on the ssh server.
I will ALSO WARN YOU that if you're using cygwin (highly recommended) you also need in your cygwin home directory a ".ssh" folder and to create a:
"config"
"id_rsa"
Files containing your config:
Host yoursshserverhost.com
  HostName yoursshserverhost.com
  Port 22
  User your_user
  IdentityFile ~/.ssh/id_rsa
  AddressFamily inet
  BatchMode yes
  ForwardAgent yes
  ClearAllForwardings yes

The id_rsa is your "key" you need to export from your ssh server.  I don't have that handy at the moment but there is information online how to make an ssh key.  Once you made it on your server you cat it and you can copy and past it into another "id_rsa" file on your server.  You can also name it whatever you want "my_special_super_secret_key" as long as you point to it in your config in the .ssh folder in your cygwin home directory.
So:

*

*sql dump

*gzip with rsyncable option

*rsync over ssh for secure backup / file copy diffs

RW


text:
Q: Prevent OpenGL from Buffering Frames I am writing a program that requires extremely low latency texture to screen streaming (under 10ms), I have implemented this using GL_ARB_buffer_storage which works great for the streaming, and vsync to prevent tearing.
However I have discovered that the NVidia pipeline will buffer from 2 to 8 frames when calling swap buffers before it blocks, I need to prevent this.
What I have done is the following:
uint64_t detectPresentTime()
{
  // warm up first as the GPU driver may have multiple buffers
  for(int i = 0; i < 10; ++i)
    glxSwapBuffers(state.renderer);

  // time 10 iterations and compute the average
  const uint64_t start = microtime();
  for(int i = 0; i < 10; ++i)
    glxSwapBuffers(state.renderer);
  const uint64_t t = (microtime() - start) / 10;

  // ensure all buffers are flushed
  glFinish();

  DEBUG_INFO("detected: %lu (%f Hz)", t, 1000000.0f / t);
  return t;
}

Then in the draw thread I do the following:
uint64_t presentTime = detectPresentTime();
if (presentTime > 1000)
  presentTime -= 1000;

while(running)
{
  const uint64_t start = microtime();
  glClear();

  // copy the texture to the screen

  glxSwapBuffers();

  const uint64_t delta = microtime() - start;
  if (delta < presentTime)
  {
    glFlush();
    usleep(delta);
    glFinish();
  }
}

This solution works great on NVidia hardware but is reported to not calculate a proper present time on AMD GPUs.
Is there a better way to do this? I know that glFinish normally shouldn't be used in an application except for profiling, but I can't find another way to ensure the GPU pipeline is not buffering frames.
Edit: For those interested this effectively emulates FastSync under Linux, but without disabling vsync.
Edit2: Perhaps the present time function should be implemented a bit different:
uint64_t detectPresentTime()
{
  glFinish();

  // time 10 iterations and compute the average
  const uint64_t start = microtime();
  for(int i = 0; i < 10; ++i)
  {
    glxSwapBuffers(state.renderer);
    glFinish();
  }
  const uint64_t t = (microtime() - start) / 10;

  DEBUG_INFO("detected: %lu (%f Hz)", t, 1000000.0f / t);
  return t;
}

A: I found the answer, there is a little known OpenGL extension called SGI_video_sync, using this it is possible to wait for the next frame.
ie:
glFlush();
uint remainder;
glXWaitVideoSyncSGI(1, 0, &remainder);


text:
Q: Scheduling Employees - what data structure to use? Question
I'm trying to write a simple employee Scheduling software for about 10-20 people in my software development company. After some consideration I settled on writing a web app in Python, Ruby or PHP + Postgres/MySQL DB. While designing database models I began to wonder what data structure would actually be the best for that kind of application.
What it will look like
Example of app showing the month view would be similar to this:
 OCTOBER    1 2 3 4 5 6 7 8 9 ...
John Apple  M M A A N N O O O ...
Daisy Pear  O O O M M A A N N ...
Steve Cat   A A N N O O O M M ...
Maria Dog   N N O O O M M A A ...

where M -> for Morning shift; A -> Afternoon shift etc. (letters can be changed to codes)
What data structure or database design would be the best for this?
I was thinking about storing strings (max of 31 characters -> 1 char , 1 day) similar to -> "MMAANNOOOAAMMNNAAOO..." for each user; Month table would contain such strings for each employee.
What would you suggest?

A: A quick answer first:

*

*EmployeeID

*Date

*ShiftType

That said, the best database design largely depends on what you're going to do with the data.  If all you need to do is store the records and display them in a table similar to you example, your approach (while not elegant) would work.
However, if you're going to retrieve the data or run reports, you're going to want something a little more structured than a string where each character represents the type of shift assignment.

A: I would go with three-table Kimball star (Date, Employee, Schedule), because sooner or later you will be asked to create (demanding) reports out of this. Who worked most nights? Who worked most weekends? Who never works weekends? Why am I always scheduled Friday afternoon? On which day of a week are certain employees most likely not to show up? Etc, etc...
Tables would be:
TABLE dimDate (
    KeyDate
  , FullDate
  , DayOfWeek
  , DayNumberInWeek
  , IsHoliday
  ,... more here
)

You can pre-fill dimDate table for 10 years, or so -- may need to tweak the "IsHoliday" column from time to time.
Employee table also changes (relatively) rarely.
TABLE dimEmployee (
    KeyEmployee
  , FirstName
  , LastName
  , Age
  , ... more here
)

Schedule table is where you would fill-in the work schedule, I have also suggested "HoursOfWork" for each shift, this way it is easy to aggregate hours in reports, like: "How many hours did John Doe work last year on holidays?"
TABLE
factSchedule (
    KeySchedule  -- surrogate PK
  , KeyDate      -- FK to dimDate table
  , KeyEmployee  -- FK to dimEmployee table
  , Shift        -- shift number (degenerate dimension)
  , HoursOfWork  -- number of work hours in that shift
)

Instead of having the surrogate KeySchedule, you could also combine KeyDate, KeyEmployee and Shift into a composite primary key to make sure you can not schedule same person on the same shift the same day. Check this on the application layer if the surrogate key is used.
When querying, join tables like:
SELECT SUM(s.HoursOfWork)
 FROM factSchedule AS s
 JOIN dimDate      AS d ON s.KeyDate = d.KeyDate
 JOIN dimEmployee  AS e ON s.KeyEmployee = e.KeyEmployee
WHERE e.FirstName='John'
  AND e.LastName='Doe'
  AND d.Year = 2009
  AND d.IsHoliday ='Yes';

If using MySQL it is OK to use MyISAM for storage engine and implement your foreign keys (FK) as "logical only" -- use the application layer to take care of referential integrity.
Hope this helps.

A: I'd suggest a more noramlized database, e.g. a table for persons and one which is the product of shift information for a perdon and a date.


text:
Q: IPython Notebook display every line output without print I would like IPython Notebook to display every line output without explicitly using the print command. Example:
a, b, c = 1, 2, 4
a
b
c
would only display 4 in the output cell, but I would like it to display
1
2
4
Is there a way to do this? I would also be able to selectively suppress some lines (by using ;?)

A: The answer is
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

Type that on a cell, run it, and from then on each command will display its own output. source

If you don't want to see the output of a particular command, just end it with ";" source

A: This isn't exactly what you're looking for, but if you just want to see the output of multiple variables, you can list the expressions with comma in between: a, b, c would display 1, 2, 4


text:
Q: Does a real linear function $l : \mathbb{C}^n\to\mathbb{R}$ satisfy $l(iz) = l(z)$? I'm working on a problem that deals with a real linear function from $l:\mathbb{C}^n\to\mathbb{R}$.  I have a guess for how to solve the problem, but it involves being able to somehow "know" what happens to $l(iz)$ for some $z\in\mathbb{C}^n$.  Am I able to deduce that $l(z)=l(iz)$ or some sort of similar relationship or is that just hoping too high?

A: The desired property does not hold. Consider the function $f : \mathbb{C} \to \mathbb{R}$ given by $f(x + iy) = x$. This is real linear, but $f(i(x + iy)) = f(-y + ix) = -y$ which is not equal to $x$ in general.
In fact, the property only holds for the zero function. If $l : \mathbb{C}^n \to \mathbb{R}$ is real linear and $l(iz) = l(z)$, then
$$l(z) = l(iz) = l(i(iz)) = l(-z) = -l(z),$$
so $l(z) = 0$.


text:
Q: Visual Studio android, deployment: 'Installation succeeded but the applications was not found on the device' Hi I have an app for android (ARM) which I want to debug. I have successfully done so using the emulator but issues arise with real hardware. When I debug the app get the error:
Could not install application 'com.appname' (pathtoapp\appname.apk) on the device '10.0.1.29:5555'. Installation succeeded but the applications was not found on the device.

Not sure whats going on here, I'm using a Nexus 5X running android 8.0.0 if that matters. I have tried using both wifi and USB for debugging with the same result. The app is actually transferred to the phone each time and I can run it from there but I need the debug to work. Anybody have a clue whats going on?
also the error message is not a typo on my part, it really is grammatically incorrect.


text:
Q: Using transient in a closure I've tried to rewrite memoize for use on a single thread using transients instead of atoms to see if it is faster in my scenario but it works only for the first 8 calls. Why? Here is the code (Clojure 1.8):
(defn transient-memoize [f]
  (let [mem (transient {})]
    (fn [& args]
      (let [v (mem args ::none)]
        (if (= v ::none)
          (let [ret (apply f args)]
            (assoc! mem args ret)
            ret)
          v)))))

(defn slow-add [x y]
  (println "slow-add" x y)
  (Thread/sleep 10)
  (+ x y))

(defn call-add [memoizer]
  (let [f (memoizer slow-add)]
    (reduce +
            (for [i (range 10)
                  _ (range 2)]
              (f 100 i)))))

(call-add memoize)

slow-add 100 0
slow-add 100 1
slow-add 100 2
slow-add 100 3
slow-add 100 4
slow-add 100 5
slow-add 100 6
slow-add 100 7
slow-add 100 8
slow-add 100 9
=> 2090

(call-add transient-memoize)

slow-add 100 0
slow-add 100 1
slow-add 100 2
slow-add 100 3
slow-add 100 4
slow-add 100 5
slow-add 100 6
slow-add 100 7
slow-add 100 8
slow-add 100 8 ; <- called second time
slow-add 100 9
slow-add 100 9 ; <- called second time
=> 2090

UPDATE
It does work if I initialize the transient map so it is a TransientHashMap instead of TransientArrayMap. It appears as if transient map, unlike normal map, does not auto convert from ArrayMap to HashMap as collection grows. Is that always the case?
(defn transient-memoize [f]
  (let [mem (transient (hash-map ::force-hash-map ::force-hash-map))]
    (fn [& args]
      (let [v (mem args ::none)]
        (if (= v ::none)
          (let [ret (apply f args)]
            (assoc! mem args ret)
            ret)
          v)))))


text:
Q: SQL: SELECT TOP with ORDER BY clause does not return correct result I have a SELECT TOP query with an ORDER BY clause that does not return the correct result. Below is a sample query and its output.
Any suggestion / workaround / solution ?
Query:
CREATE TABLE #TestTop
(
    TopID INT,
    TopStr VARCHAR(MAX)
)

INSERT INTO #TestTop VALUES(1749, '');
INSERT INTO #TestTop VALUES(1750, '');
INSERT INTO #TestTop VALUES(1752, 'z');
INSERT INTO #TestTop VALUES(1739, 'a');

SELECT * FROM #TestTop ORDER BY TopStr ASC

SELECT TOP 1 * FROM #TestTop ORDER BY TopStr ASC

SELECT TOP 4 * FROM #TestTop ORDER BY TopStr ASC

DROP TABLE #TestTop;

Result:

[SELECT *]

TopID       TopStr
----------- -----------
1749
1750
1739        a
1752        z

[SELECT TOP 1]

TopID       TopStr
----------- --------------
1750

[SELECT TOP 4]

TopID       TopStr
----------- --------------
1750
1749
1739        a
1752        z

A: You have not specified complete ordering, so the database (whichever one it is) is entitled to return rows that match on TopStr in any order it wants. Just because your first query happens to give the ordering you want is luck, and that could change based on a database upgrade / load on the system / many other factors.
You need to add the TopId into the ordering list if you want results to be ordered by that column as well as TopStr.

A: The problem here is the column that's been used for sorting: the original statements use the TopStr column and, since all its values are equal, the order in which the rows are returned is unspecified. To correct your statement just use the proper column TopID, as follows:
CREATE TABLE #TestTop
(
    TopID INT,
    TopStr VARCHAR(50)
)

INSERT INTO #TestTop VALUES(1749, '');
INSERT INTO #TestTop VALUES(1750, '');
INSERT INTO #TestTop VALUES(1752, '');
INSERT INTO #TestTop VALUES(1739, '');

SELECT '' [_ALL_],* FROM #TestTop ORDER BY TopID ASC
SELECT TOP 1 '' [TOP_1], * FROM #TestTop ORDER BY TopID ASC
SELECT TOP 4 '' [TOP_4], * FROM #TestTop ORDER BY TopID ASC

DROP TABLE #TestTop;

A: Try this, it works in sql server
SELECT TOP 4 * FROM #TestTop
order by ROW_NUMBER() OVER(ORDER BY (CASE WHEN TopStr = '' THEN NULL ELSE TopStr END))

OR
SET ROWCOUNT 4
SELECT * FROM #TestTop ORDER BY TopStr ASC
SET ROWCOUNT 0


text:
Q: Unable to load service using `service xxx start` I'm trying to run a service with a script in the /etc/init.d/aaa with sudo service aaa start, there's such an script with content like these:
!/bin/sh

CATA_HOME=/home/pi/proxy

case $1 in
    start)
            sh $CATA_HOME/startup.sh
            ;;
    stop)
            sh $CATA_HOME/shutdown.sh
            ;;
    restart)
            sh $CATA_HOME/shutdown.sh
            sh $CATA_HOME/startup.sh
            ;;
    *)

            echo 'please use : aaa {start | stop | restart}'
    ;;
esac
exit 0

and the result tends to be Failed to start aaa.service: Unit aaa.service not found.


text:
Q: how to activate a new /etc/hosts instantly I'm using a terminal command to replace the /etc/hosts - file.
alias nonews="sudo -S chattr -i /etc/hosts < /etc/password_file && sudo -S cp /etc/hosts_all_blocked /etc/hosts < /etc/password_file && sudo -S chattr +i /etc/hosts < /etc/password_file"

Where the hosts_all_blocked is a file with which distracting webpages are blocked.
And the /etc/password_file contains the sudo-password.
So after using I want the relevant pages to be blocked immediately. I tried the command and sometimes it works immediately as wished, but sometimes even if the file has changed, there is no effect on the possibility to open webpages.
How can I ensure that the changes in the /etc/hosts are having an immediate effect?
Btw: For the unblocking I'm using a 20-minute delay:
alias getnews="sleep 1200 && sudo -S chattr -i /etc/hosts < /etc/password_file && sudo -S cp /etc/hosts_all_allowed /etc/hosts < /etc/password_file && sudo -S chattr +i /etc/hosts < /etc/password_file"

A: Browsers will often keep a local copy of DNS lookups in their cache to save a little bit of time when loading sites. This means that you'll need to clear the cache of the browser in order for changes to the /etc/hosts file to be seen for already-loaded sites (including those that may have been loaded in previously closed tabs).
With this in mind, you may want to expand your alias to a shell script that also removes the browser cache (but leaves cookies intact ... unless you want to start with a "fresh" browser that knows nothing about your past usage each and every time).
If you use Firefox as your main browser, you can clear the cache via a shell script with this command:
rm -r ~/.cache/mozilla/firefox/*.default*/*

If you use Google Chrome as your main browser, you can clear the cache like this:
rm ~/.cache/google-chrome

For other browsers, you will need to dig through the ~/.cache directory to find where they keep their temporary resources.
Note that these commands should be run as the user, not with sudo.


text:
Q: FCC / Local Weather App / JSON information not displaying info from the OpenWeather API I am doing the freeCodeCamp Local Weather App Zipline Challenge, and got to the part where I have extracted my location using an IP-Location API, and am supposed to use the location with the Open Weather API to get information about the local weather.
I've done this successfully and opening the JSON links in a new tab in my Browser(Chrome) displays the JSON with all the objects/arrays/info I need/etc.
However, were I to try and log this info to the console or change an html element's contents with specific information from the callback info, I get nothing. Not even any errors.
I did some research and tried to use http instead of https on my codepen, but that didn't solve the problem. I also tried going through some Youtube tutorials, but nobody else encountered the issue.
I have included code snippets with all of my code from the codepen(NOTE: I removed the api key for the local weather app)
Here are some useful links:
1. The challenge info itself: https://www.freecodecamp.com/challenges/show-the-local-weather
2.The IP API I used to get my location: http://ip-api.com/
3.The Open Weather API: https://openweathermap.org/current#geo
EDIT: To make my question more clear: Why does the info I get from the API not display in the HTML elements specified in the jQuery function?

$(document).ready( function() {
        var city;
        var countryCode;

        $.getJSON("http://ip-api.com/json",function(data2){
            city = data2.city;
            countryCode = data2.countryCode;

          var api = "api.openweathermap.org/data/2.5/weather?q="+city+","+countryCode+"&APPID=MYKEYGOESHERE";
          $.getJSON(api, function(data3){
            $("cityName").html(data3.city);
            $("temperature").html(data3.temp);
            $("weather").html(data3.weather[0].description);
          });
      });
  });

body{
  color:#FFF;
  background-color: #f4495d;
}
.mainContainer{
  margin:7% auto;
  background-color: #ce2336;
  width:50%;
}

h2{
  text-align:center;
  font-size: 180%;
}

p{
  text-align:center;
  font-size: 150%;
}

The Local Weather APP

something something

YourCity

TheTemperature

TheWeather

A: okay based on the comment, you need to fill the html that you are creating, to do this, you have to put "#" character in order to fill a specific element, so your code should be
$(document).ready( function() {
    var city;
    var countryCode;

    $.getJSON("http://ip-api.com/json",function(data2){
        city = data2.city;
        countryCode = data2.countryCode;

      var api = "api.openweathermap.org/data/2.5/weather?q="+city+","+countryCode+"&APPID=MYKEYGOESHERE";
      $.getJSON(api, function(data3){
        $("#cityName").text(data3.city);
        $("#temperature").text(data3.temp);
        $("#weather").text(data3.weather[0].description);
      });
  });

});