text:
Q: Cross checking if value in column 1 is X, value in column 2 should be Y So I got 2 columns whereby they have different values but are dependent. I want to find those that are not showing the correct values. I really am stumped about what to do.
SELECT *

Let's take those value ends with html should have a value of 3 in the answer column,py should have a value of 4 in the answer column, jpg should have a value of 5 in the answer column and Null should reflect Null in the answer column

webpage
answer

abc.html
3

xyz.py
4

qrs.html
2

syt.jpg
5

NULL
1

Result should show

webpage
answer

qrs.html
2

NULL
1

A: You can use CASE to check for all those possible combinations. For example:
select t.*,
  case
    when webpage like '%.html' then
      case when answer = 3 then 'VALID' else 'INVALID' end
    when webpage like '%.py' then
      case when answer = 4 then 'VALID' else 'INVALID' end
    when webpage like '%.jpg' then
      case when answer = 5 then 'VALID' else 'INVALID' end
    when webpage is null then
      case when answer is null then 'VALID' else 'INVALID' end
    else 'Unrecognized webpage'
  end as validation
from t

EDIT:
If you only want to show the invalid ones then you can do:
select *
from (
  select t.*,
    case
      when webpage like '%.html' then
        case when answer = 3 then 'VALID' else 'INVALID' end
      when webpage like '%.py' then
        case when answer = 4 then 'VALID' else 'INVALID' end
      when webpage like '%.jpg' then
        case when answer = 5 then 'VALID' else 'INVALID' end
      when webpage is null then
        case when answer is null then 'VALID' else 'INVALID' end
      else 'Unrecognized webpage'
    end as validation
  from t
) x
where validation <> 'VALID'

A: SELECT
  *
FROM
  your_table
WHERE
     (webpage LIKE '%.html' AND answer <> 3)
  OR (webpage LIKE '%.py'   AND answer <> 4)
  OR (webpage LIKE '%.jpg'  AND answer <> 5)
  OR (webpage IS NULL       AND answer IS NOT NULL)

A: You can try using CASE to check in WHERE condition:
SELECT *
  FROM test
   WHERE CASE WHEN webpage LIKE '%html' AND answer=3 THEN 1
              WHEN webpage LIKE '%py' AND answer=4 THEN 1
              WHEN webpage LIKE '%jpg' AND answer=5 THEN 1
              WHEN webpage IS NULL AND answer IS NULL THEN 1
           ELSE 0 END = 0

Fiddle


text:
Q: Using SlowCheetah Config Transforms on Web.config in a 3.5 Web Forms app I downloaded SlowCheetah into an old .Net 3.5 web forms application in order to add transforms to web.config.
I've used SlowCheetah with Windows Services and Console Applications to transform app.config with success in the past. In those cases, the config gets transformed and placed in the bin as ApplicationName.exe.config.
However, with this web forms application, the config file never ends up in the bin, as web forms sites are built with just .dll's dropped in the bin and IIS points to the root directory to run the site. So instead of the web.config getting included in the build process and packaged up in the bin, it's just left alone in the root location.
No transforms are being applied to the web.config in the root, which is a good thing, since the web.config in the root directory is in source control and is the file which we perform the transform on.
I would be happy with getting the web.config to be included in the build so that slowCheetah transforms it and then drops it in the bin. We would then have to manually take it out of the bin and put it back in the root level on our servers, but it would be worth it to have the transforms.
Does anyone know how to get the transforms to run against my web.config or get it included in the build process so slowCheetah can work its magic?
Thanks!

Update
I modified the properties of the web.config and it is now included in the build, however, the transformations are still not being applied to it.
Build Action: Embedded Resource
Copy to Output Director: Copy Always

A: Solution
I renamed the Web.config in our source control to Web.template.config and added transforms Web.template.Debug.config and Web.template.Release.config
Next, unload the project file and edit the .csproj xml adding the following elements
This creates a new Web.config file in the root directory. Woot!
<PropertyGroup>
  <PrepareForRunDependsOn>
    $(PrepareForRunDependsOn);
    WebConfigTransform;
  </PrepareForRunDependsOn>
</PropertyGroup>
<Target Name="WebConfigTransform">
  <Message Text="Configuration: $(Configuration): Web.template.$(Configuration).config" />
  <TransformXml Source="Web.template.config"
                Transform="Web.template.$(Configuration).config"
                Destination="Web.config" />
</Target>

A: Found a better solution - one without renaming files to .template.config.
Paste the following into your Web Forms .csproj file.
  <Target Name="BeforeBuild">
    <Delete Files="$(TEMP)\Web.TEMP.config" />
    <Copy SourceFiles="Web.config" DestinationFiles="$(TEMP)\Web.TEMP.config" />
    <TransformXml
      Source="$(TEMP)\Web.TEMP.config"
      Transform="Web.$(Configuration).config"
      Destination="Web.config" />
  </Target>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selenium python proxy не работает страница Изучаю selenium есть вот такой код:
print("введите просто название без .txt")
txter = input("Введите откуда брать пароли и логины и тд: ")
txt = txter+'.txt'
f = open(txt)

User_Agent = f.readline()
if User_Agent == "\n":
    print("впишите User-Agent в файл")
else:
    print("")
    ninja = User_Agent

proxy_host = f.readline()
if proxy_host == "\n":
    print("Кажется я должен работать без прокси...")
    option = webdriver.FirefoxOptions()
    option.set_preference("dom.webdriver.enabled", False)
    option.set_preference("general.useragent.override", ninja)
    driver = webdriver.Firefox(options=option)
else:
    print("Кажется я должен рабоать с прокси...")
    proxy_port = f.readline()
    proxy_login = f.readline()
    proxy_password = f.readline()
    if proxy_login == "\n":
        print("Кажется нету логина от прокси...")
        print("Не советуем использовать бесплатные прокси!")
        if proxy_password == "\n":
            print("Кажется нету пароля от прокси...")
            PROXY_HOST=proxy_host
            PROXY_PORT=proxy_port
            fp = webdriver.FirefoxProfile()
            fp.set_preference('network.proxy.type', 1)
            fp.set_preference('network.proxy.http', PROXY_HOST)
            fp.set_preference('network.proxy.http_port', PROXY_PORT)
            fp.set_preference('network.proxy.https', PROXY_HOST)
            fp.set_preference('network.proxy.https_port', PROXY_PORT)
            fp.set_preference('network.proxy.ftp', PROXY_HOST)
            fp.set_preference('network.proxy.ftp_port', PROXY_PORT)
            fp.set_preference('network.proxy.ssl', PROXY_HOST)
            fp.set_preference('network.proxy.ssl_port', PROXY_PORT)
            fp.set_preference('network.proxy.no_proxies_on', '')

            option = webdriver.FirefoxOptions()
            option.set_preference("dom.webdriver.enabled", False)
            option.set_preference("general.useragent.override", ninja)
            driver = webdriver.Firefox(options=option, firefox_profile = fp)
        else:
            print("Здесь что-то не так!")
            sys.exit()
    else:
        proxy_options = {
            "proxy": {
                "https": f"http://{proxy_login}:{proxy_password}@"+proxy_host+":"+proxy_port
            }
        }
        option = webdriver.FirefoxOptions()
        option.set_preference("dom.webdriver.enabled", False)
        option.set_preference("general.useragent.override", ninja)
        driver = webdriver.Firefox(options=option, seleniumwire_options=proxy_options)
        print("OK")

       driver.get('https://browser-info.ru/')

при переходе пишет вот это:

а в CMD пишет:
Traceback (most recent call last):
  File "iBot.py", line 604, in <module>
    menu()
  File "iBot.py", line 157, in menu
    driver.get('https://browser-info.ru/')
  File "C:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 333, in get
    self.execute(Command.GET, {'url': url})
  File "C:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Python\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=redirectLoop&u=https%3A//browser-info.ru/&c=UTF-8&d=Firefox%20%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D0%B8%D0%BB%2C%20%D1%87%D1%82%D0%BE%20%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%20%D0%BF%D0%B5%D1%80%D0%B5%D0%BD%D0%B0%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D1%8F%D0%B5%D1%82%20%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81%20%D0%BD%D0%B0%20%D1%8D%D1%82%D0%BE%D1%82%20%D0%B0%D0%B4%D1%80%D0%B5%D1%81%20%D1%82%D0%B0%D0%BA%D0%B8%D0%BC%20%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%BC%2C%20%D1%87%D1%82%D0%BE%20%D0%BE%D0%BD%20%D0%BD%D0%B8%D0%BA%D0%BE%D0%B3%D0%B4%D0%B0%20%D0%BD%D0%B5%20%D0%B7%D0%B0%D0%B2%D0%B5%D1%80%D1%88%D0%B8%D1%82%D1%81%D1%8F.

A: не получится авторизоваться на прокси. и попытаться заполнить алерт с авторизацией тоже не получится потому что не поддерживается.
единственное что может помочь - seleniumwire.
$: pip install selenium-wire

from seleniumwire import webdriver

options = {
    'proxy': {
        'http': 'http://user:pass@192.168.10.100:8888',
        'https': 'http://user:pass@192.168.10.100:8888',
        'no_proxy': 'localhost,127.0.0.1'
    }
}
driver = webdriver.Firefox(seleniumwire_options=options)
driver.get("https://whoer.net")

P.S. или подождите несколько дней. я как раз заканчиваю дополнение, чтобы можно было ставить прокси с авторизацией и куки. но это не точно)
P.P.S. https://github.com/alexsok-bit/selenium_helper

A: мне помогло только одно это удаление подмены User-Agent или случайный выбор тоесть вот так:
user_list = ["Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; MATP; MATP)", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)"]
ninja = random.choice(user_list)
print(ninja)

option = webdriver.FirefoxOptions()
option.set_preference("dom.webdriver.enabled", False)
option.set_preference("general.useragent.override", ninja)
driver = webdriver.Firefox(options=option)
driver.get('https://browser-info.ru/')

также можно еще можно вот так:
ninja = "'"+user-agent+"'"


text:
Q: ajax text variable passing 0 or NaN I'm trying to pass the  variable var_nome  to a php file using the code bellow.
The value of this var is coming from a text field in a html form. If the value of the field is a number, it works perfectly and I get the data on teh php page BUT if the value of var_nome is a text, I got 'NaN' as a result?

function AlteraNomePortfolioAjax(portfolios_id, var_nome, SuccessDiv) {
  $.ajax({
    type: 'POST',
    dataType: 'text',
    url: 'PRT_ope_ajax.php',
    data: {
      'portfolios_id': +portfolios_id,
      'var_nome': +var_nome
    },
    cache: false,
    success: function(data) {
      $(SuccessDiv).html(data);
    }
  });
}

A: Remove that + sign, it is attempting to convert the variables to an integer:
data: {'portfolios_id' : portfolios_id , 'var_nome' : var_nome  },


text:
Q: Difference between QUESTIONS and Query when i check status from MySQL console it shows 104 questions, ... and in the MySQL general log it shows 18 Queries !
Q1 -> what is the difference between Question and Query ?
Q2 -> For a standard site what should be an ideal limit for questions and queries per page [in forum/social networking] ?

A: As per the manual:

Queries. The number of statements executed by the server. This variable includes statements executed within stored programs, unlike the Questions variable. It does not count COM_PING or COM_STATISTICS commands. This variable was added in MySQL 5.0.76.
Questions. The number of statements executed by the server. As of MySQL 5.0.72, this includes only statements sent to the server by clients and no longer includes statements executed within stored programs, unlike the Queries variable. This variable does not count COM_PING, COM_STATISTICS, COM_STMT_PREPARE, COM_STMT_CLOSE, or COM_STMT_RESET commands.


text:
Q: Adding a fixed number of rows in datagridview in c# in the .cs design form I am trying to create a datagridview with 25 rows containing three columns and next option for going to next records of a local database,containing employee name id.employee and view profile button.but cant add a single row from the tool box..how is it possible to do in the design form?

A: *

*Drag drop DataGridView control.

*In Form_Load event write:

datagridView1.RowCount = 25;


text:
Q: JqueryUi splitButton not showing in the browser Hi guys I'm a jquery noobie, just started jqueryUI
Problem OverView:
I'm trying to use jqueryUI tabs inside which there is a JqueryUI Split Button (which is not being rendered). Cheddar ,Mushrooms and Bocon are suppose to be rendered as split buttons.
I have copied markup and jquery from the sites so I wouldn't make any mistake but still it doesn't work.
Firefox snapshot

Code:
I created a jsfiddle for you guys , but it is not working as it was in my browser.
Jquery
    <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css"
    rel="Stylesheet" />


text:
Q: Static Signals in QT Im looking for the elegant pattern to follow the events of all instances of a class. So in theory it should be possible to emit a signal as from the class either directly or within a static method (which doesn't seem to be necessary then) because:
The connect() method declares a sender and the signature of it. In this case it could be the class. There is no specific expectation to the sender. As far as I understood, the signal itself is an object on the event stack, oriented to the sender. It shouldn't matter where is was generated(in a static or non static context/method).
So in general: what might be the issue with declaring the signal a static function other that expect the object signalling it is a valid Instance of the class.
It is already possible now through a helper-instance (e.g. the first instance) of the same class (referable through a static public pointer within the class) or for clarification of a specific helper class instance. Then one has to connect to that static pointer and through that, listen to all of them. Every Instance has then indirectly emit through it by
helperInstance->staticEmit(signalFoo,this);

So the question is: is there a more direct/elegant way or should QT look into this?

A: In theory, Qt Could implement this feature, by basically adding code generation for the helper object code you showed  to the moc compiler.
Because any signal is a function declaration, of which the implementation is generated by the moc compiler. This implementation is basically just a:
for( auto& slot: connected_slots):
    slot.object->slot.function()

(very simplified)
this connected_slots needs to live somewhere. ie. it is a variable, which needs to be stored in memory.
So in any case you are going to need an object of some kind to store this in. This is normally in the QObject base class.
My guess for the reason that they didn't add this, is because the Qt framework is very object oriented, and the added complexity outweighs the benefits.


text:
Q: How to render axios call correctly in React Native? I have created a component to return the price value when a coin name is passed to the component.
In the console output inside function, it is showing the result but not returning the value.
My code:
MarketPrice.js
import React, { useEffect, useState } from "react";
import { Text } from "react-native";
import axios from "axios";

function round(num) {
  var m = Number((Math.abs(num) * 100).toPrecision(15));
  return (Math.round(m) / 100) * Math.sign(num);
}

const goForAxios = async (coin) => {
  //setLoading(true);

  const response = await axios.get(
    `https://min-api.cryptocompare.com/data/price?fsym=${coin}&tsyms=INR`
  );
  console.log(response.data.INR.toString());
  return response.data.INR.toString();
};

export default function MarketPrice(props) {
  console.log(props.coin);
  const marketPrice = goForAxios(props.coin);
  // return marketPrice;
  console.log("MarketPrice: " + marketPrice);
  return <Text>{round(marketPrice)}</Text>;
}

The output in UI is showing as NaN
And on console:
119.12
ADA
BTC
3058216.2

A: You're trying to use the return value of an asynchronous function which won't quite work (as it returns a Promise - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). A better approach would be to add a result state which can be conditionally rendered (depending on the value of props.coin)
export default function MarketPrice(props) {
  const [result, setResult] = useState(null);

  const goForAxios = async (coin) => {
    const response = await axios.get(
      `https://min-api.cryptocompare.com/data/price?fsym=${coin}&tsyms=INR`
    );
    setResult(response.data.INR);
  };

  const marketPrice = goForAxios(props.coin);
  console.log(result);
  return
Market Price: {result ? round(result) : "Not Found"}
;
}


text:
Q: How to customize UI Dialogs in Wix to modify location/size of Labels I've been wanting to modify the location of the InstallDirDlgDescription text (Click Next to install to the default folder or click Change to choose another.)
The x co-ordinate of this text by default is X="25" and the text overlaps with my logo (I've customized the dialog to change the banner to my logo).
I know I can change the VALUE of the String by doing -->
<String Id="InstallDirDlgDescription">This is a custom message.</String>

But is there a way of changing the location of the text (I want to set X = "5" so that the text shifts to left and doesn't overlap with my logo) ?
Thanks !

A: Use the UI element to change control attributes. See http://www.joyofsetup.com/2012/07/14/localizing-more-than-strings-in-wix-v3-6/ for examples.


text:
Q: 16.04 Installation stuck on "Creating ext4 file system", previously had trouble with partitioning I'm trying to install Ubuntu 16.04 over a virus-filled Windows 8.1 desktop. I've tried using DBAN to wipe out the Windows 8.1 partition, but the USB I installed it on doesn't show up on the boot menu. I think the virus-filled Windows 8.1 partition is what's giving me problems, but I can't be sure.
My installation usually crashes on the step where I have to create a partition. After launching Windows and restarting about 15 times, I've somehow gotten Ubuntu to start installing, but it has now been stuck on "Creating ext4 file system" for over an hour. Any help would be greatly appreciated!


text:
Q: Unable to append in an existing .txt file I'm unable to append in existing .txt file as it overwrites the older data written in the file. Please help me out by telling me where am I getting wrong.
This is the a class file(Orderact.java) which is related to file handling.
     String data="\nName- " + partyn + "; ndate- " + dt + "; product- " + prosel + "; qty- " + qty + ";";
                    // Create the folder if required.
                    File f = new File(Environment.getExternalStorageDirectory() + "/fb");
                    if(!f.exists()) {
                        String path = Environment.getExternalStorageDirectory() + "/fb";
                        File folder = new File(path);
                        folder.mkdirs();
                    }
                    String path = Environment.getExternalStorageDirectory() + "/fb";
                    File folder = new File(path);
                    File file = new File(folder, "testing.txt");
                    try {
                        if(!file.exists()) {
                            // Create the file.
                            file.createNewFile();
                            FileOutputStream fOut = new FileOutputStream(file);
                            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                            myOutWriter.append(data);
                            myOutWriter.close();
                            fOut.flush();
                            fOut.close();
                            Toast.makeText(Orderact.this, "Saved", Toast.LENGTH_LONG).show();
                        } else {
                            FileOutputStream fOut = new FileOutputStream(file);
                            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                            myOutWriter.append(data);
                            myOutWriter.close();
                            fOut.close();
                            Toast.makeText(Orderact.this, "Saved", Toast.LENGTH_LONG).show();
                        }

                    } catch (IOException e) {
                        Toast.makeText(Orderact.this, "Something went wrong.\n Not Saved", Toast.LENGTH_LONG).show();
                        Log.e("Exception", "File write failed: " + e.toString());
                    }

A: You need to open your file in apppend mode, as follows
Change
FileOutputStream fOut = new FileOutputStream(file);

to
FileOutputStream fOut = new FileOutputStream(file, true);

Please refer to FileOutputStream javadoc


text:
Q: When enough is enough This user has now probably made around 15 accounts. He consistently uses the python, python-3.x, mod-wsgi, wsgi and mysql-python tags, and does not ever do anything constructive. This deleted question was his latest.
Unfortunately I haven't been bookmarking his other questions, but here are some of his previous accounts:

*

*https://stackoverflow.com/users/2403148/american-patriot

*https://stackoverflow.com/users/2391328/patriot-american

*https://stackoverflow.com/users/2398036/allah-akbar-club-members

*https://stackoverflow.com/users/2373557/python-newbie

*https://stackoverflow.com/users/2372142/python-newbie
He has also gone by many other names (Iraq War Veteran is the one that comes to mind), but those accounts have been deleted.

Is there nothing we can do about this? Deleting and suspending his accounts just seems to give him more reason to create other accounts. Is there a way to block him entirely?

Edit: this new question seems to have been deleted by Community ♦

A:
Is there a way to block him entirely?

Well... Maybe...
But if that's not convenient, just flag and move on. The mods are used to this clown, and have no qualms about just destroying new accounts as they come in. I've been keeping my own little list as well.

A: Being the main deleter of this guy's questions, I can give you a few tips.

*

*Don't comment on his posts (he likes the attention)

*-1, vote to close, and flag for a quick deletion

*He will give up eventually, he is trying to prove some point about religion, or the government, eventually he'll realise that he isn't going to get much of a response out of us. It has gotten to the point where I personally enjoy deleting his posts.

* Also you can change his post title to "Spam" so that more people can close it quickly
EDIT: As expected, he has now disappeared


text:
Q: Importing libgdx project into Eclipse Juno error Cannot find .apk I am just starting to learn Libgdx, and am in the process of importing the 4 projects[desktop, main java game, android, html] into Eclipse Juno. I have not added any lines of code, just trying to get them to run on the different platforms.
It runs fine on the desktop version, but when I tried to run it in the Android emulator I get the error. Cannot find mygdxgame.apk!
I realized that my gen folder is completely empty, there is no R.java for the project. I have tried a number of things to make this work, but none of it is working. I am listing the things I have tried so far, and the hopefully the reason why I am asking this repeatedly asked question.

*

*Project > Clean

*Package Explorer [right click on my project] > Android Tools > Fix Project Issues

*Deleted gen folder and Project > Clean

*Restarted Eclipse

*Deleted the project and Imported it again

*Set Compiler Compliance Level to 1.6 for both main java game and Android project

*Added a dummy XML to the android project and tried clean, and deleted it

*Unchecked and rechecked Build Automatically

*Checked my target-sdk in project.properties and made sure it is the same Project Properties -> Android and in my Manifest.xml

*[Right click on project] > Properties > Java Build Path > Source tab, Removed mygdxgame/gen folder and then added it again

*Made sure Project Properties > Android > Is Library is unchecked

Nothing has worked so far. My gen folder is still empty and I am unable to run the Android project because of the same error. Cannot find mygdxgame.apk!
What else can I do to fix this? In case this is answered I would appreciate someone giving me a link to the solution, as I have been pouring through SO and Google in general for nearly 2 hours now, with no success.
Regs

A: What happened to me a few days ago:

*

*1.- I got the SDK Tools 22 update and I installed it, no other update appeared in my sdk manager... so I closed it.

*2.- Then I got that "NO APK" error and tried every answer I could find.

*3.- I opened SDK manager again, and I noted SDK Platform Tools also got an update and there was a new one: SDK Build Tools. Both of them didn't show up when I first updated the SDK Tools.. so.
ANSWER:
Open SDK Manager and check if your SDK Tools, SDK Platform Tools, SDK Build Tools are updated :)

A: On your build path, you should have a reference to the main project, under Projects tab of Java Build Path. Under Libraries, you should have gdx-backend-android.jar and gdx.jar along with Android not being a library.
Please check if Android is set as a library. If so, uncheck it. To do that, right click on the project and then select Properties. Choose Android on the left panel of the new window. Uncheck Is Library if checked.
Here's something might help-
Unable to run Android app, Could not find .apk issue in eclipse

A: I would take  alook at your buildpath if all libs are correct. If it's  a projekt from an other computer the libs are often at different places so you need to correct those manual. If they are not correct the android projekt do not generate your R. class and so on. So do rightclick on the core projekt -> Buidl Path -> Configure Build Path. Now take a look at the libs if all are there. I had the same issue with the android 15 apk so i need to add it manual. The clean or such do not fix such because eclipse can't know where you have all your libs.

If you really dont get it run i would recoment to use the setup ui of libgdx. It does noramlly handle all imports and so on for you. You can also use it to update your current projekt and so on.
Else i would read the guide for Manual Project Setup of Libgdx.
Libgdx setup Guide
I hope this does fix it.


text:
Q: Explicit Expression for Homotopy Group As I have known, we can write down an explicit expression for $\pi_n(S^n)=\mathbb{Z}$, taking $\pi_2(S^2)$ as an example:
Consider a smooth map: $\mathbb{R}^2\rightarrow S^2$ that assign $x\mapsto \vec{n}(x)$, where $\vec{n}$ is a three-dimensional unit vector whose tip defines a point on the 2 sphere $S^2$. Suppose $\vec{n}$ tends to the same unit vector $\vec{n}(\infty)$ at large distance in all directions. We can identify the base manifold as $\mathbb{R}^2\cup \{\infty\}=S^2$: then we have:
$$N=\frac{1}{4\pi}\int_{\mathbb{R}^2}\epsilon_{ijk}n^i\partial_xn^j\partial_yn^k dxdy\in \mathbb{Z}=\pi_2(S^2)$$
My question is:
Is it possible to write down similar simple expression for all homotopy group? For example, $\pi_4(S^3)=\mathbb{Z}_2$ and Hopf map $\pi_3(S^2)=\mathbb{Z}$  ?


text:
Q: Allowing K8S daemonset to exist in the global pid namespace I'm trying to configure a daemonset to run on the global pid namespace resulting the ability to see other processes in the host, including the containers' processes.
I couldn't find an option to achieve this.
In general, what I'm looking for is close to the sidecar container shareProcessNamespace attribute only on the host level.

A: There is an attribute that allows this - hostPID: true
So the yaml file should looks something like that:
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: busybox
spec:
  selector:
    matchLabels:
      name: busybox
  template:
    metadata:
      labels:
        name: busybox
    spec:
      hostPID: true
      containers:
      - name: busybox
        image: busybox
        command: [ "sh", "-c", "sleep 1h" ]

More info in:

*

*https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces

*https://medium.com/@chrispisano/limiting-pod-privileges-hostpid-57ce07b05896


text:
Q: Azure DevOps - Boards - Link Work Item with Deployment I can't make Deployment Widget of a Work item view to work.
I have a Product Backlog item defined as follows:

As you can see i have linked this work item in the "Development" widget to master branch
I also enabled my release pipeline to log to Report deployment status to Boards

And despite multiple commits to master triggering build and that triggering release still in my ticket the Deployment widget does not show those releases. I must miss some setup work here.
I was expecting something similar to this:
(Screenshot of Tim Corey)

A: So my initial idea was invalid. This link is based on the text of the commit.
Work item has id 16.
I commit code with a message "Fix invalid user registration link #16".
Then the pipelines are executed and then the release is bound to the work item in the Deployment widget.
This is the result


text:
Q: How to set up Tomcat for one Database Connection per Request I have a Sparkjava app which I have deployed on a Tomcat server. It uses SQL2O to interface with the MySQL-database. After some time I start to have trouble connecting to the database. I've tried connecting directly from SQL2O, connecting through HikariCP and connecting through JNDI. They all work for about a day, before I start getting Communications link failure. This app gets hit a handful of times a day at best, so performance is a complete non issue. I want to configure the app to use one database connection per request. How do I go about that?
The app doesn't come online again afterwards until I redeploy it (overwrite ROOT.war again). Restarting tomcat or the entire server does nothing.
Currently every request creates a new Sql2o object and executes the query using withConnection. I'd be highly surprised if I was leaking any connections.
Here's some example code (simplified).
public class UserRepositry {
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected Sql2o sql2o = new Sql2o("jdbc:mysql://mysql.server.name/dbname?serverTimezone=UTC", "username", "password");

    public List<Users> getUsers() {
        return sql2o.withConnection((c, o) -> {
            return c.createQuery(
                    "SELECT\n" +
                            "  id,\n" +
                            "  name\n" +
                            "FROM users"
            )
                    .executeAndFetch(User.class);
        });

    }
}

public class Main {
    public static void main(String[] args) {
        val gson = new Gson();

        port(8080);

        get("/users", (req, res) -> {
            return new UserRepository().getUsers();
        }, gson::toJson);
    }
}

A: If you rely on Tomcat to provide the connection to you: It's coming from a pool. Just go with plain old JDBC and open that connection yourself (and make sure to close it as well) if you don't like that.
So much for the answer to your question, to the letter. Now for the spirit: There's nothing wrong with connections coming from a pool. In all cases, it's your responsibility to handle it properly: Get access to a connection and free it up (close) when you're done with it. It doesn't make a difference if the connection is coming from a pool or has been created manually.
As you say performance is not an issue: Note that the creation of a connection may take some time, so even if the computer is largely idle, creating a new connection per request may have a notable effect on the performance. Your server won't overheat, but it might add a second or two to the request turnaround time.
Check configurations for your pool - e.g. validationQuery (to detect communication failures) or limits for use per connection. And make sure that you don't run into those issues because of bugs in your code. You'll need to handle communication errors anyways. And, again, that handling doesn't differ whether you use pools or not.
Edit: And finally: Are you extra extra sure that there indeed is no communication link failure? Like: Database or router unplugged every night to connect the vacuum cleaner? (no pun intended), Firewall dropping/resetting connections etc?


text:
Q: CUDA: documentation of kernel CRT? I'm trying to find the documentation for all of the functions available for the CUDA kernels.
The CUDA Reference manual seem to include only the host functions and the CUDA programming guide only includes some details such as the accuracy of these functions but not their documentation.
Am I missing something or does this piece of documentation simply doesn't exist?

A: Appendices B and C of the CUDA Programming Guide contain documentation for functions that can be executed within kernels.  Mostly they are for things like texture fetches, atomic instructions, warp voting, synchronization, and C standard library mathematical operations.
The documentation is very sparse because the meaning of these functions is described elsewhere, in the C standard library documentation.  Some of these functions are quite esoteric.  The meaning of others can be guessed at from the name.  For the ones that you do not recognize, you can google for the man page with a query such as "site:opengroup.org nextafter".  If you are on a *nix machine and have the C library documentation installed, typing man nextafter will also work.


text:
Q: How can I read system information in Python on OS X? Following from this OS-agnostic question, specifically this response, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from OS X using Python (including, but not limited to memory usage).

A: You can get a large amount of system information from the command line utilities sysctl and vm_stat (as well as ps, as in this question.)
If you don't find a better way, you could always call these using subprocess.

A: The only stuff that's really nicely accesible is available from the platform module, but it's extremely limited (cpu, os version, architecture, etc). For cpu usage and uptime I think you will have to wrap the command line utilities 'uptime' and 'vm_stat'.
I built you one for vm_stat, the other one is up to you ;-)
import os, sys

def memoryUsage():

    result = dict()

    for l in [l.split(':') for l in os.popen('vm_stat').readlines()[1:8]]:
        result[l[0].strip(' "').replace(' ', '_').lower()] = int(l[1].strip('.\n '))

    return result

print memoryUsage()

A: I did some more googling (looking for "OS X /proc") -- it looks like the sysctl command might be what you want, although I'm not sure if it will give you all the information you need.  Here's the manpage: http://developer.apple.com/DOCUMENTATION/Darwin/Reference/ManPages/man8/sysctl.8.html
Also, wikipedia.

A: i was searching for this same thing, and i noticed there was no accepted answer for this question.  in the intervening time since the question was originally asked, a python module called psutil was released:
https://github.com/giampaolo/psutil
for memory utilization, you can use the following:
>>> psutil.virtual_memory()
svmem(total=8374149120L, available=2081050624L, percent=75.1, used=8074080256L, free=300068864L, active=3294920704, inactive=1361616896, buffers=529895424L, cached=1251086336)
>>> psutil.swap_memory()
sswap(total=2097147904L, used=296128512L, free=1801019392L, percent=14.1, sin=304193536, sout=677842944)
>>>

there are functions for cpu utilization, process management, disk, and network as well.  the only omission from the module is a function for retrieving load average, but the python stdlib has os.getloadavg() if you are on a UNIX-like system.
psutil claims to support Linux, Windows, OSX, FreeBSD and Sun Solaris, but i have only tried OSX mavericks and fedora 20.

A: Here's a MacFUSE-based /proc fs:
http://www.osxbook.com/book/bonus/chapter11/procfs
If you have control of the boxes you're running your python program on it might be a reasonable solution.  At any rate it's nice to have a /proc to look at!


text:
Q: display each item in the array without using a loop Hi i have this certain php function. But i cannot figured it out how to output this one. This is the question // Given an array, display each item in the array without using a loop. (Do not use built in functions to do this, like PHP's print_r; use a recursive function to implement)
and this is the code
<?php
  function print_array(array $input)
  {
  }
?>

can someone share ideas on this? Any help is muchly appreciated.

A: you can use implode
$your_array = array("abc", "5", "xyz")

$text  = implode(" ", $your_array); // implode with space you can use any other on this place

echo $text;

OUTPUT : abc 5 xyz
FUNCTION :
function print_array($your_array)
{
   $text  = implode(" ", $your_array); // implode with space you can use any other on this place

    echo $text;
}

Recusive Method :
but only used when the key of the array is numeric starting with 0, 1, 2 ....
print_array($your_array);

function print_array($your_array, $index=0)
{
    if(isset($your_array[$index]))
    {
        echo $your_array[$index];
        $index+=1;
        print_array($your_array, $index)
    }
}


text:
Q: How do you select the text within  using Xpath? I'm trying to get the text within pre tags in C# which uses Xpath. The webpage only consists of the following:

<body>
    <pre>
        The text I am trying to select
    </pre>
</body>

I can't seem to select just that text and I don't exactly know how to put that in a string. This is the code I'm using:

var WebgetME2_ = new HtmlWeb();
var docME2_ = WebgetME2_.Load(webpage); //loading the webpage
HtmlNode NODEME2_ = docME2_.DocumentNode.SelectSingleNode("//*/pre"); //select the node
string innerME_ = NODEME2_.InnerText; //put the node innertext in string
// After getting the text within the <pre> tags I want to select a part of it using RegEx, that's why I need it in a string
string imagineME2_ = Regex.Match(innerME_, "(?=http)(.+?)(?<=.jpg)").ToString();

A: I've found a way to bypass the problem.
System.Net.WebClient WebclientME_ = new System.Net.WebClient();
byte[] rawME_ = WebclientME_.DownloadData(webpage); //download page
string innerME_ = System.Text.Encoding.UTF8.GetString(rawME_); //write to a string
string imagineME2_ = Regex.Match(innerME_, "(?=http)(.+?)(?<=.jpg)").ToString();

It downloads the page which I'm not fond of because it works slower but it works.

A: Please try below Xpath :-
/body/pre/text()

text() function will retrieve all text for you from the path you have mentioned in the Xpath
pre should be the child of body.. If it is not your real structure then use double slash // .... // means it will find the pre node from your complete DOM.
You can also give a try with below Xpath:-
/body//pre/text()

Hope it will help you :)


text:
Q: Why do I get array our of range in MQL4? I am trying to make an indicator that shows when x candles of the same color appear on the chart. But I am getting an array out of range error.

*

*There is a up and down array buffer (an arrow pointing up or down)

*minCandles is an extern integer that determines after how many bars to point the arrow.

*the bear part works but from right to left.

I think the problem may be in down[i] = Low[i] but I don't know why.
Here is the code:
//+------------------------------------------------------------------+
//|                                                       SlayEm.mq4 |
//|                               Copyright 2016, Sebastian Bonilla. |
//|                                  https://www.sebastianbonilla.me |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, Sebastian Bonilla."
#property link      "https://www.sebastianbonilla.me"
#property description "show X amount of candles of the same color."
#property version   "1.00"
#property strict
#property indicator_chart_window

//--- input parameters
extern int minCandles = 4;
double up[];
double down[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
SetIndexBuffer(0,up); //assign up to the first buffer
SetIndexStyle(0,DRAW_ARROW);
SetIndexArrow(0,233);
SetIndexLabel(0, "Up Arrow");

 //stuff for 1
  SetIndexBuffer(1,down); //assign down to the second buffer
  SetIndexStyle(1,DRAW_ARROW);
  SetIndexArrow(1,234);
  SetIndexLabel(1, "Down Arrow");
 //---
return(INIT_SUCCEEDED);
}
  //+------------------------------------------------------------------+
  //| Custom indicator iteration function                              |
 //+------------------------------------------------------------------+
  int OnCalculate(const int rates_total,
            const int prev_calculated,
            const datetime &time[],
            const double &open[],
            const double &high[],
            const double &low[],
            const double &close[],
            const long &tick_volume[],
            const long &volume[],
            const int &spread[])
  {//------------------------------------------

int limit = MathMax(rates_total-prev_calculated,2);
int i;
int bull_count = 0;
int bear_count = 0;

for (i = 1; i < limit; i++){

//--bears-----------------------------------------------------------------------------------
if(Open[i] >= Open[i-1]){
   bear_count++;
   if (bear_count > minCandles) up[i] = High[i];
}
else bear_count = 0;   // this by itself works but from right to left

// --- bulls ----------------------------------------

if(Open[i] < Open[i-1]){
   bull_count++;
   if (bull_count > minCandles) down[i] = Low[i];
}
else bull_count = 0;  //this part creates the array out of range error*/

}

Comment((string)bear_count+ " --- ", (string)bull_count +" --- ", (string)i);

 //--- return value of prev_calculated for next call
 return(rates_total);
 }

//+------------------------------------------------------------------+

A: There are a few strange things behind the writing a fast and efficient [ Custom Indicator ] MQL4-code.
First, the real-time headache coming from a design decision to accumulate all the computational efforts from all the present [ Custom Indicator ] into a single thread.
While this is hidden, it increases the pressure to minimise all execution latencies at a cost of the colculus being operated in segmented mini-batches, from the deepest history ( the bars farthest back to the left ) proceeding iteratively forwards to the right, towards the current Bar.
One might get confused from the concept of reversed-numbering of the Bars, starting from [0]-for the most recent Bar ( the live Bar ), counting up, while going deeper and deeper towards the history on the far left.
If it were not enough, there are some additional prohibited things inside a [ Custom Indicator ], but as your web-page shows that you provide [ Custom Indicator ] programming on a commercial basis, it is worthless to repeat 'em here again.

Production-grade code for [Custom Indicator] ought have at least:

*

*protective fuses

*minimised main duty-cycle overheads

*zero raw-Comment()-s to avoid damages to GUI/MMI

#property strict

//--- input parameters
extern int    minCandles = 4;

//--- input PROTECTIVE FUSES:

       int    minCandlesFUSED = MathMax( 2, minCandles );               // assign no less than 2 irrespective of the extern
       double up[];
       double down[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit() {

 // indicator buffers mapping
    SetIndexBuffer( 0, up );                                            // assign up[] to the first buffer
    SetIndexStyle(  0, DRAW_ARROW );
    SetIndexArrow(  0, 233 );
    SetIndexLabel(  0, "Up Arrow" );

 // stuff for 1
    SetIndexBuffer( 1, down );                                          // assign down[] to the second buffer
    SetIndexStyle(  1, DRAW_ARROW );
    SetIndexArrow(  1, 234 );
    SetIndexLabel(  1, "Down Arrow" );

 // RET
    return( INIT_SUCCEEDED );
    }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate( const int       rates_total,
                 const int       prev_calculated,
                 const datetime &time[],
                 const double   &open[],
                 const double   &high[],
                 const double   &low[],
                 const double   &close[],
                 const long     &tick_volume[],
                 const long     &volume[],
                 const int      &spread[]
                 ) {
 // ------------------------------------------

    int          limit  = rates_total
                        - prev_calculated
                        + minCandlesFUSED;
    if (  Bars + limit <  minCandlesFUSED + 1 ) return( 0 ); // --> JIT/RET( 0 )
                                //               ^--------------------^--- MEANING-FULL value, ref prev_calculated mechanisation
                                // makes no sense to start indicator w/o at least minCandlesFUSED + 1 Bars ready
    int bull_count = 0;
    int bear_count = 0;

    for ( int i = limit + 1;    // iterator .SET             to start [limit + 1] Bars back in time (towards left), moving forwards -> [0]
              i > 0;            // iterator .PRE-CONDITION   to keep looping while i > [0] points to already exist. Bars->[1], leaving [0] out
              i--               // iterator .DEC             on loop-end, before re-testing next loop .PRE-CONDITION
              ){
       // --------------------------------------------------------------BEARS
          if (  Open[i] >= Open[i-1] ){
                bear_count++;
                if (  bear_count > minCandlesFUSED ) up[i] = High[i];   // ref. above the
          }
          else  bear_count = 0;                                         // this by itself works

       // --------------------------------------------------------------BULLS
          if (  Open[i] < Open[i-1] ){
                bull_count++;
                if (  bull_count > minCandlesFUSED ) down[i] = Low[i];
          }
          else  bull_count = 0;                                          // this part creates the array out of range error*/

    }

    Comment( (string)bear_count                                         // rather use StringFormat( "TEMPLATE: %d UP --- %d DN --- ", bear_count,
           + " --- ",                                           //                                                            bull_count
             (string)bull_count                                         //                          )
           + " --- "
             );

    return( rates_total );                                              // return( rates_total ) value becomes -> prev_calculated for the next call
    }
//+------------------------------------------------------------------+


text:
Q: Jquery mobile "Save as bookmark" button in jquery mobile, for my library book list, Good day friends....please help me out in need to make a  "Save as bookmark" button in jquery mobile, for my library book list, where by you can view the bookmarked books in another page or delete them...?
The app contains books and a list view just like a book store where by any book you click on can be bookmarked

A: Try this small function:
JavaScript:

HTML:
Bookmark This Page

EDIT:
IE will show an error if you don't run it off a server (it doesn't allow JavaScript bookmarks via JavaScript when viewing it as a file://....


text:
Q: Cron has troubles running Rscript through a bash script Hi I have a simple cron task  0 0 * * 1 /usr/bin/env bash /home/(me)/Downloads/news-scrape/weekly.sh. In the "weekly.sh" script I have
#! /bin/bash

Rscript script.r

##remaining code, simple bash if else statement

In the "script.r" Rscript, I have a rather complex scraping algorithm using Rselenium and some other packages. Now weekly.sh runs as intended in the terminal but when I call that cron task I get this error message
Fatal error: cannot open file '/home/erdman.35/Downloads/tdai-news-scrape-master/srcript.r': No such file or directory
find: 'report.csv': No such file or directory
No new news articles found
Can't stat report.csv: No such file or directory
report.csv: unable to attach file.

Now report.csv is an output of the rscript, so the main issue is the lack of the Rscript executing properly, I have "chmod +x"'d it so it's executable and still it doesn't run. Any idea what my issue may be?


text:
Q: VBA find returns "nothing" in userform I have a worksheet in which column "A" to "I" are filled with data. Column a contains dates from 30/11/2011 to 6/12/2011. I have a userform in which there are 2 optionbuttons. When the first is selected, all dates are used. When the second is selected 6 textboxes that can be used to enter a start- and an enddate. These dates are used to create a range with the all data/the selected interval. I used .find to make a range of the selected start- and enddate.
I wrote a code for this which works in a seperate module, but i can't get it to work within the userform because range.Find returns "nothing." It took me a while to get it to work in the module as well because range.find is difficult to use in combination with dates but now that it works I dont know why it doesn't work in the Userform.
I've searched the forum extensively but couldn't find anything that helps me. I hope it's just a typing error but I really can't find why it doesn't work.
This is the code in the module:
sub Find()
Dim Dates As Range
Dim Data As Range
Dim LastRow As Long
Dim LastCol As Long

Dim RngStart As Range
Dim RngEnd As Range
Dim RngDates As Range
Dim DateStart As String
Dim DateEnd As String

Dim TextboxDate1 As Long   'these variables represent the textboxvalues of the userform
Dim TextboxDate2 As Long
Dim TextboxMonth1 As Long
Dim TextboxMonth2 As Long
Dim TextboxYear1 As Long
Dim TextboxYear2 As Long
    TextboxDate1 = 2
    TextboxDate2 = 4
    TextboxMonth1 = 12
    TextboxMonth2 = 12
    TextboxYear1 = 2011
    TextboxYear2 = 2011

    ThisWorkbook.Worksheets("blad1").Activate
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row
    LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
        Set Data = Range(Cells(1, 2), Cells(LastRow, LastCol))
        Set Dates = Range(Cells(1, 1), Cells(LastRow, 1))

DateStart = TextboxMonth1 & "/" & TextboxDate1 & "/" & TextboxYear1 '"12/2/2011"
DateEnd = TextboxMonth2 & "/" & TextboxDate2 & "/" & TextboxYear2 '"12/4/2011"
    Set RngStart = ThisWorkbook.Worksheets("blad1").Columns("A").find(DateStart)
    Set RngEnd = Columns("a").find(what:=DateEnd, after:=Cells(1, 1), searchdirection:=xlPrevious)
    Set RngDates = Range(RngStart, RngEnd)
        MsgBox RngDates.Address 'should return A160:A447
End Sub

however, when I try to run this code in the userform, .find returns "nothing"
Dim Dates As Range
Dim Data As Range
Dim LastRow As Long
Dim LastCol As Long
Dim RngStart As Range
Dim RngEnd As Range
Dim RngDates As Range
Dim DateStart As String
Dim DateEnd As String

ThisWorkbook.Worksheets("blad1").Activate

    LastRow = Cells(Rows.Count, 1).End(xlUp).Row
    LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
        Set Data = Range(Cells(1, 2), Cells(LastRow, LastCol))
        Set Dates = Range(Cells(1, 1), Cells(LastRow, 1))

If OptionButton1.Value = False And OptionButton2.Value = False Then
    MsgBox "specify time domain"
End If

If OptionButton1.Value = True Then
    Set RngDates = ThisWorkbook.Worksheets("blad1").Range(Cells(2, 1), Cells(LastRow, 1))
End If

If OptionButton2.Value = True Then
    DateStart = TextboxMonth1 & "/" & TextboxDate1 & "/" & TextboxYear1 '"12/2/2011"
    DateEnd = TextboxMonth2 & "/" & TextboxDate2 & "/" & TextboxYear2 '"12/4/2011"
        Set RngStart = ThisWorkbook.Worksheets("blad1").Columns("A").find(DateStart)
        Set RngEnd = Columns("a").find(what:=DateEnd, after:=Cells(1, 1), searchdirection:=xlPrevious)
        Set RngDates = Range(RngStart, RngEnd)
            MsgBox RngDates.Address 'should return A160:A447
End If

I can see that DateStart and DateEnd are properly defined, the code just doesn't manage to return the cells where the dates are found and gives me a runtime error 1004: method 'range of object '_global' failed, because i tried to set rngdates as a range from nothing to nothing.
Edit: It might be help to know that when i run the entire code with the first optionbutton selected i can afterwards use the seperate module to create the range RngDates however, when i run the code using the second selection and i stop it after it crashes, the seperate module won't find the desired cells either.
edit: to clarify it's about the dates december 2nd 2011 to december 4th 2011, not february.
Thanks in advance

A: When you use .Find to set RngStart, you specify the workbook and worksheet, but when you use .Find to get RngEnd you don't specify the worksheet.
This may lead to a failure to Find.

A: I filled column A of worksheet "Sheet1" with some dates.
I created a form with the following controls:

*

*Text box: txtDate

*Command button: cmdFind

*Label: lblResult

This is the code within the form:
Private Sub cmdFind_Click()

  Dim Rng As Range
  Dim DateDat As Date

  With Worksheets("Sheet1")

    DateDat = CDate(txtDate)

    Set Rng = .Columns("A").Find(What:=DateDat)

    If Rng Is Nothing Then
      lblResult.Caption = Format(DateDat, "d mmm yyyy") & " not found"
    Else
      lblResult.Caption = Format(DateDat, "d mmm yyyy") & " found in " & _
                          Replace(Rng.Address, "$", "")
    End If

  End With

End Sub

Each time I enter a date into the text box and click the button, the result of the Find is displayed in the label.  CDate is a bit fussy about what constitutes a date but apart from this I have no difficulty in finding dates with this code.
Note the variable in the Find statement is of type Date.


text:
Q: ng-change not working on a text input I am new to angular js. In my code there is color picker initialized from a text field. User changes the value of color and I want that color to be reflected as a background of a text in a span. It is not working. What is missing?
HTML:

   <input type="button" value="set color" ng-click="myStyle={color:'red'}">
   <input type="button" value="clear" ng-click="myStyle={}">
   <input type="text" name="abc" class="color" ng-change="myStyle={color:'green'}">

   Sample Text

myStyle={{myStyle}}

Plunker - http://plnkr.co/edit/APrl9Y98Em0d6rxuzRDE?p=preview
However when I change it to ng-click it works.

A: I've got the same issue, my model is binding from another form, I've added ng-change and ng-model and it still doesn't work:
<input type="hidden" id="pdf-url" class="form-control" ng-model="pdfUrl"/>

<ng-dropzone
  dropzone="dropzone"
  dropzone-config="dropzoneButtonCfg"
  model="pdfUrl">
</ng-dropzone>

An input #pdf-url gets data from dropzone (two ways binding), however, ng-change doesn't work in this case. $scope.$watch is a solution for me:
$scope.$watch('pdfUrl', function updatePdfUrl(newPdfUrl, oldPdfUrl) {
  if (newPdfUrl !== oldPdfUrl) {
    // It's updated - Do something you want here.
  }
});

Hope this help.

A: ng-change requires ng-model,
<input type="text" name="abc" class="color" ng-model="someName" ng-change="myStyle={color:'green'}">

A: When you want to edit something in Angular you need to insert an ngModel in your html
try this in your sample:
    <input type="text" name="abc" class="color" ng-model="myStyle.color">

You don't need to watch the change at all!

A: Maybe you can try something like this:
Using a directive
directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

A: One can also bind a function with ng-change event listener, if they need to run a bit more complex logic.

        <input type='text' ng-model='name' ng-change='change()'>

 changed {{counter}} times

...
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
      $scope.name = 'Australia';
      $scope.counter = 0;
      $scope.change = function() {
        $scope.counter++;
      };
});

https://jsfiddle.net/as0nyre3/1/

A: First at all i'm seing your code and you haven't any controller. So i suggest that you use a controller.
I think you have to use a controller because your variable {{myStyle}} isn't compile because the 2 curly brace are visible and they shouldn't.
Second you have to use ng-model for your input, this directive will bind the value of the input to your variable.


text:
Q: How can is draw rectangle based on two date? Below is the code i use to draw axis and circle. I need to add rectangle based on two date and placed it under the circle. Appreciate your help. Thanks.

                    let scale: any = d3select.scaleTime()
                        //.domain([d3select.min(data), d3select.max(data)])
                        .domain([new Date(2020, 0, 1), new Date(2021, 0, 1)])
                        .range([20, axes_width - 800]);

                    let x_axis: any = d3select.axisBottom(scale)
                        .scale(scale);

                    axes_svg.append("g")
                        .call(x_axis);

                    var myData = [new Date(2020, 3, 1), new Date(2020, 6, 1)];

                    axes_svg
                        .selectAll('circle')
                        .data(myData)
                        .enter()
                        .append('circle')
                        .style("fill", "#69b3a2")
                        .attr('r', 6)
                        .attr('cy', 40)
                        .attr('cx', function (d) {
                            return scale(d);
                        });

A: I think your problem here is that you pass all dates in a one dimensional array. Instead of having
var myData = [new Date(2020, 3, 1), new Date(2020, 6, 1)];
like you do for the circles, you should have something like this:
var myRecData = [ {"startDate": new Date(2020, 3, 1), "endDate": new Date(2020, 6, 1)}, {"startDate": new Date(2020, 4, 1), "endDate": ....];
And then access it with d.startDate and d.endDate
EDIT:
Based on your last comment I recreated the whole code (for future questions please  add a complete reproducible code, so people who want to help you can test it fast...):


text:
Q: How do I unzip a .zip/.rar file in Node.js into a folder I am using zlib along with fstream now for zipping and sending to the client, Now I need to unzip an archive(which may contains sub folders) into a folder maintaining the folder structure. How do I do that?

A: Rar is a closed-source software. The only way you can do it -- install command-line rar (rar.exe or linux version of rar, which is available on most platforms) and call it by means of this:
var exec = require('child_process').exec;

exec("rar.exe x file.rar", function (error) {
    if (error) {
     // error code here
    } else {
      // success code here
    }
});

A: There are plenty of node modules that can do this for you. One of them is node-unzip. You can extract a .zip file to a directory as simple as this.
fs.createReadStream('path/to/archive.zip').pipe(unzip.Extract({ path: 'output/path' }));
Further reading: https://github.com/EvanOxfeld/node-unzip

A: you can use this amazing module http://node-machine.org/machinepack-zip
for uncompress a zip file with directory structure inside zip
var Zip = require('machinepack-zip');

// Unzip the specified .zip file and write the decompressed files/directories as contents of the specified destination directory.
Zip.unzip({
   source: '/Users/mikermcneil/stuff.zip',
   destination: '/Users/mikermcneil/my-stuff',
}).exec(callbackSuccess, callbackFail );

for download remote file and unzip you can use this code:
        var fs = require('fs');
    var unzip = require("unzip2");
    var tar = require('tar');
    var zlib = require('zlib');
    var path = require('path');
    var mkdirp = require('mkdirp'); // used to create directory tree
    var request = require("request");
    var http = require('http');
    var zip = require("machinepack-zip");

    for (var i = 0; i < _diff.length; i++) {
        request(constants.base_patch +"example.zip")
            request = http.get({ host: 'localhost',
                                     path: '/update/patchs/' +  "example.zip",
                                     port: 80,
                                     headers: { 'accept-encoding': 'gzip,deflate' } });

            request.on('response', (response) => {
                var output = fs.createWriteStream(__dirname + "/tmp/" +"example.zip");

                  switch (response.headers['content-encoding']) {
                    // or, just use zlib.createUnzip() to handle both cases
                    case 'gzip':
                      response.pipe(zlib.createGunzip()).pipe(unzip.Extract({ path: __dirname }));
                      break;
                    case 'deflate':

                      response.pipe(zlib.createInflate()).pipe(unzip.Extract({ path: __dirname }));
                      break;
                    default:
                      response.pipe(output);
                      break;
                  }
            })

            request.on('close', function(){
                zip.unzip({
                    source: __dirname + "/tmp/" + "example.zip",
                    destination: __dirname,
                }).exec({
                    error: function (err){
                     alert("error")
                    },

                    success: function (){
                     //delete temp folder content after finish uncompress
                    },
                });
            })
    }

note : remove unnecesary modules.

A: Use node js decompress-zip, first install it with npm:
npm install decompress-zip --save

Then you have to require it:
const DecompressZip = require('decompress-zip');

Finally you can use it in the following way:
let unzipper = new DecompressZip( absolutePathFileZip );

The directory to be extracted must be specified:
unzipper.extract({
    path: pathToExtract
});

Additional you can use the following for better control:
Handle Error:
unzipper.on('error', function (err) {
      console.log('event error')
 });

Notify when everything is extracted
unzipper.on('extract', function (log) {
    console.log('log es', log);
});

Notify "progress" of the decompressed files:
unzipper.on('progress', function (fileIndex, fileCount) {
    console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);
});

A: If anyone looking for async-await way syntax:
const request = require('request');
const unzip = require('unzip');

await new Promise(resolve =>
            request('url')
                .pipe(fs.createWriteStream('path/zipfilename'))
                .on('finish', () => {
                    resolve();
                }));

await new Promise(resolve =>
            fs.createReadStream('path/filename')
                .pipe(unzip.Extract({ path: 'path/extractDir }))
                .on('close', ()=>{
                    resolve()
                }));


text:
Q: возможно ли сделать мобильное приложение из одного webview? Добрый день
У меня стоит задача, сделать мобильную версию своего saas сервиса под андроид и ios
но сам я владею только веб разработкой
мне пришла идея сделать приложение-оболочку, в которой будет только вызов webview с зашитым адресом(url) и все,
а весь контент будет загружаться с сервера
тогда я смогу сам развивать приложение и не нужно будет делать адаптацию под разные платформы (андроид и ios и другие)
я уже попробовал сделать такое приложение на адроиде, результат мне понравился
Теперь вопрос:
насколько я знаю, подобное приложение не разместят в appstore, есть ли какой то способ распространять такое приложение для ios?
спасибо

A: Если вы знаете веб, посмотрите React Native (javascript который компилируется в нативное приложение) или Cordova (javascript который запускается в веб вью).
Для любопытных, почему если просто загрузить сайт в веб вью эпл не пропустит в аппстор:

4.2 Minimum Functionality
  Your app should include features, content, and UI that elevate it beyond a repackaged website. If your app is not particularly useful, unique, or "app-like," it doesn't belong on the App Store. If your App doesn't provide some sort of lasting entertainment value, or is just plain creepy, it may not be accepted. Apps that are simply a song or movie should be submitted to the iTunes store. Apps that are simply a book or game guide should be submitted to the iBooks Store.

A: Из личного опыта - создавал приложение, состоящее из одного webView в который выводился частично добавленный в пакет код сайта. Основные страницы брались потом из web. Приложение успешно размещено в App Store.
Другой опыт: приложение с небольшим нативным функционалом, все остальное загружается из web. Приложение также в App Store.
Apple опасается, что на ревью вы подадите один сайт, а после выхода подставите другой. Поэтому какой-то минимум надо зашить в приложение, можно в виде небольшого сайта.


text:
Q: Android Instrumentation Test Runner: How to filter multiple test annotations The documentation for instrument is clear on how to filter a single test annotation from a test run:

Filter test run to tests without given annotation: adb shell am instrument -w -e notAnnotation com.android.foo.MyAnnotation com.android.foo/android.test.InstrumentationTestRunner

(from https://developer.android.com/reference/android/test/InstrumentationTestRunner.html)
Is it possible to filter multiple annotations? I have not found a syntax that works thus far. I have tried:

*

*adb shell am instrument -w -e notAnnotation com.android.foo.MyAnnotation -e notAnnotation com.android.foo.AnotherAnnotation com.android.foo/android.test.InstrumentationTestRunner

*adb shell am instrument -w -e notAnnotation com.android.foo.MyAnnotation,com.android.foo.AnotherAnnotation com.android.foo/android.test.InstrumentationTestRunner

*adb shell am instrument -w -e notAnnotation com.android.foo.MyAnnotation com.android.foo.AnotherAnnotation com.android.foo/android.test.InstrumentationTestRunner

*adb shell am instrument -w -e notAnnotation "com.android.foo.MyAnnotation","com.android.foo.AnotherAnnotation" com.android.foo/android.test.InstrumentationTestRunner
and probably others that I've forgotten, thus far to no avail.
Anyone know how to do this?

A: You should be using AndroidJUnitRunner anyway:

Filter test run to tests without any of a list of annotations:
adb shell am instrument -w -e notAnnotation com.android.foo.MyAnnotation,com.android.foo.AnotherAnnotation com.android.foo/android.support.test.runner.AndroidJUnitRunner


text:
Q: How to wait until the the page loads in Selenium IDE other than waitforpageload? I have a problem when running the test cases because the time take for loading the page is different in each time. I have tried WaitforPageLoad and also checking for visual elements but it was not helping.
WaitforPageLoad always wait for specific seconds and checking visual elements wont work all the time since after loading the page there won't be any new elements in some pages.
Could anyone suggest a better idea ?

A: You could increase the amount of time you wait for a page load:

setTimeout(timeout)
      Arguments:
    timeout - a timeout in milliseconds, after which the action will return with an error

Specifies the amount of time that Selenium will wait for actions to complete.

Actions that require waiting include "open" and the "waitFor*" actions.
The default timeout is 30 seconds.

This might help. It's a bit unclear what your goal is.

A: Use the Explicit Wait on your action. For instance:
            // Tell webdriver to wait
            WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(4));

            // Test the autocomplete response - Explicit Wait
            IWebElement autocomplete = wait.Until(x => x.FindElement(By.ClassName("ac-row-110457")));


text:
Q: Fail to send email by utility class I have below utility class which throws error as this in debug log.
Error
INVALID_FIELD_WHEN_USING_TEMPLATE: When a template is specified, the plain text body, html body, subject, charset, and "treatBodiesAsTemplate" may not be specified
Utility Class
   public class AbbvieUtilitiesclass
{
    public static Map<String,String> M;
   /* public map<String, String> MyMap = new map<String, String> {'A' => 'Initial_Notification_to_Rep',
                                                            'B' => 'Initial_Notification_to_Manager_Publish',
                                                            'C' => 'Notify_DM_Manager_on_Incident_Closure',
                                                            'D'=> 'Reminder_Notification_to_Manager_and_RM',
                                                            'E'=>'Notify_Rep_on_Incident_Closure'};*/

        public static void sendTemplatedEmail(String[] toRecipients, String[] ccRecipients,Boolean CCCheck, String templateApiName) {
      //  templateId   must be ID of an Email template
      //  targetObjId must be a Contact, User, Lead Id -- also used in merge fields of template recipient.xxxx
      //  whatId    must be an SObject that is used in the merge fields of the template relatedTo.xxxx
      //  fromId    if non null, use current user, otherwise, use this ID (most likely an org wide no reply id)
      //  bcc      not permitted when using templates
     List < Messaging.SingleEmailMessage > mails = new List < Messaging.SingleEmailMessage > ();
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

    Emailtemplate template;
    try {template = [select Id, Subject, HtmlValue, Body, name from EmailTemplate where developername = : templateApiName];}
    catch (Exception e) {
      /*throw new UtilException ('[U-03] Unable to locate EmailTemplate using name: ' + templateApiName +
                    ' refer to Setup | Communications Templates ' + templateApiName);*/
    }

       // String htmlBody = Template.HtmlValue;

   // htmlBody = htmlBody.replace('{!}', 'Dear '+toRecipients );

        email.setToAddresses(toRecipients);
        if(CCCheck==true && templateApiname!='Initial_Notification_to_Manager_Publish')
       { email.setCcAddresses(ccRecipients);}
       // email.setTargetObjectId(targetObjId);
        //email.setWhatId(whatId);
       // email.setorgWideEmailAddressId(orgWideEmailId);
        email.setSubject(template.name);
       // email.sethtmlbody(htmlbody);
        //email.setTargetObjectId(targetid);
         email.settemplateid(template.id);
        email.setSenderDisplayName('Abbvie IT Team');
        email.SetSaveAsActivity(false);
      //  email.setSaveAsActivity(saveAsActivity);      // save email as activity on the targetObjId (i.e. Contact). Note activity can't be saved on Users

       /* System.debug(LoggingLevel.INFO,'** entered sendTemplatedEmail, to:' + toRecipients + ' cc:' + ccRecipients +  ' templateId:' + templateId + ' tagetObjId:' + targetObjId +
                        ' whatId:' + whatId + ' orgWideEmailId: ' + orgWideEmailId);*/
        try {
            mails.add(email);
            Messaging.sendEmail(mails);
            return;
        }
        catch (EmailException e) {/*throw new UtilException('[U-02] sendTemplatedEmail error. ' + e.getMessage());*/}

    }

}

A: Remove this line
 email.setSubject(template.name);

as error clearly  says When a template is specified, the plain text body, html body, subject, charset, and "treatBodiesAsTemplate" may not be specified
I also think you should uncomment this lines if you are using Template.
//email.setTargetObjectId(targetid);


text:
Q: Convert elasticsearch query to java with multi aggregation I am using elastichsearch in java 1.7.5 and after console query I want to tranform the code below to java code. It is a query with mutiple sub-aggregation and result in my confusion.
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "rawlog.auAid": {
              "from": "3007145536"
            }
          }
        },
        {
          "term": {
            "rawlog.ip": "118.70.204.171"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "aggs": {
    "articles_over_time": {
      "date_histogram": {
        "field": "loggedTime",
        "interval": "second"
      },
      "aggs": {
        "id": {
          "terms": {
            "field": "auAid"
          }
        },
        "url": {
          "terms": {
            "field": "urlId1"
          }
        },
        "devVerId": {
          "terms": {
            "field": "devVerId"
          }
        },
        "devTypeId": {
          "terms": {
            "field": "devTypeId"
          }
        },
        "osVerId": {
          "terms": {
            "field": "osVerId"
          }
        },
        "browserId": {
          "terms": {
            "field": "browserId"
          }
        }
      }
    }
  }
}

Can anyone help me to perform it ? Thanks so much

A: You have everything you need in the documentation here and here, but it basically goes like this:
// 1. build the query
QueryBuilder qb = boolQuery()
    .must(rangeQuery("rawlog.auAid").from(3007145536))
    .must(termQuery("rawlog.ip", "118.70.204.171"));

// 2. build the aggregations
AggregationBuilder articlesOverTime =
    AggregationBuilders
            .dateHistogram("articles_over_time")
            .field("loggedTime")
            .interval(DateHistogramInterval.SECOND);
articlesOverTime.subAggregation(AggregationBuilders.terms("id").field("auAid"));
articlesOverTime.subAggregation(AggregationBuilders.terms("url").field("urlId1"));
articlesOverTime.subAggregation(AggregationBuilders.terms("devVerId").field("devVerId"));
articlesOverTime.subAggregation(AggregationBuilders.terms("devTypeId").field("devTypeId"));
articlesOverTime.subAggregation(AggregationBuilders.terms("osVerId").field("osVerId"));
articlesOverTime.subAggregation(AggregationBuilders.terms("browserId").field("browserId"));

// 3. make the query
SearchResponse sr = node.client().prepareSearch()
    .setQuery(qb)
    .addAggregation(articlesOverTime)
    .execute().actionGet();


text:
Q: Touchscreen PC settings in Windows 7 I installed the exact same Windows 7 on two identical touch PCs.
The problem is that if I want to activate something by a button on one PC I just need to click and on the other I need to swipe.
I compared all the touchscreen settings but could not find anything. Does anyone have suggestions?


text:
Q: How can I extract audio from FLV? I need to extract the audio from a FLV file recorded using FMS. I used the SPEEX coded in my flash application that streams the audio and video to FMS.
I have tried using FFMPEG, with no luck. This is the -i outputs of my FLV:
FFmpeg version SVN-rUNKNOWN, Copyright (c) 2000-2007 Fabrice Bellard, et al.
  configuration: --enable-gpl --enable-pp --enable-swscaler --enable-pthreads --enable-libvorbis --enable-libtheora --enable-libogg --enable-libgsm --enable-dc1394 --disable-debug --enable-shared --prefix=/usr
  libavutil version: 1d.49.3.0
  libavcodec version: 1d.51.38.0
  libavformat version: 1d.51.10.0
  built on Apr 23 2010 15:11:13, gcc: 4.2.4 (Ubuntu 4.2.4-1ubuntu3)
[flv @ 0xb7ed7110]Unsupported audio codec (b)
[flv @ 0xb7ed7110]Unsupported audio codec (b)
Input #0, flv, from 'm.flv':
Duration: 00:00:05.0, start: 0.000000, bitrate: N/A
Stream #0.0: Video: flv, yuv420p, 288x203, 1000.00 fps(r)
Stream #0.1: Audio: 0x000b, 11025 Hz, mono
I need a command line utility, since this will be executed from a server.
Thanks in advance.

A: Typical flv:

flv @ 0x152ba80]Estimating duration
  from bitrate, this may be inaccurate
  [lavf] stream 0: video (flv), -vid 0
  [lavf] stream 1: audio (mp3), -aid 0
  VIDEO:  [FLV1]  320x240  0bpp  25.000
  fps  250.3 kbps (30.6 kbyte/s)

To read this, ffmpeg must be compiled with additional options:
  --enable-gpl --enable-nonfree --enable-libmp3lame

Then,
ffmpeg -i flvfile 1.mp3

A: Try this site: flv2mp3.com
Update: Sorry, I didn't read the command line part of your question.


text:
Q: Automatically signing in with AWS Cognito I've developed a backend for our iOS app with AWS, using Cognito for authentication. Currently, the app requires re-authentication each time it is launched cold. I can't store the token as they expire too frequently. I'm considering simply storing the email and password and using it to reauthenticate after the user has signed in once, but this doesn't seem like the most secure idea.
Is there a better way to automatically authenticate the user without requiring them to explicitly type in their password each time they use the app?

A: If you are using Amazon Cognito User Pools, there would be a long lived refresh token available. The SDK for iOS will have a session available so you won't need to reauthenticate the user. It has a getSession call which retrieves the tokens, uses the refresh token to get a new access token if the access token is expired.


text:
Q: Windows 10 upgrade and SSD Currently I have a laptop running Windows 7 on a HDD but I want to upgrade to Windows 10 on an SSD.
Does anyone know if it is better to upgrade to 10 first and then migrate to SSD or to do the migration before the upgrade?
Thanks in advance.

A:
Does anyone know if it is better to upgrade to 10 first and then
  migrate to SSD or to do the migration before the upgrade?

Both ways have their advantage.
Directly installing win10 on the SSD means:

*

*No leftover crud from an old win7 install

*Still got your old harddisk around in case things do not work out. (e.g. if win10 does not recognise your network card out of the box and you need to download drivers.... Whoops. Catch 22....

First upgrading win7 to win 10 means:

*

*'Licence' activation.

*and in my experience it just works, while direclty installing windows 10 was a hassle of failing to install, unclear error messages and driver problems.

A: There are some disadvantages in doing the 7->10-Upgrade from the SSD, but they are negligible:

*

*Unnecessarily writing of rather large amounts of data to the SSD (but it's only one time, so it doesn't really have an impact on wear but cosmetic)

*The Win 10 install might not be as clean after the upgrade than if you directly do a fresh install

Those are the only things I can think of. Anyway, I did it the same way: old HDD with Win7, upgrade to 10, replace HDD by SSD, then fresh install of Win10 (activates automatic).

A: I would suggest migrating then updating as I have personal experience of issues with W10 and W7 licenses.
Once you upgrade to W10 you will lose your W7 license so write it down before you upgrade. The license gets turned into a W10 license which cannot be reversed.
Also doing it this way you will know if it's the SSD or the upgrade that caused any issues you may then find you have with your system.


text:
Q: how i can delete last separator , from echo I have problems because I can't delete last, from my echo
with rtrim
  while($t= mysql_fetch_array($asd)){
    $rest = '
       "'.$t['a'].'": "'.$t['b'].'",';
    echo rtrim($rest,",");

output:
   "1": "a"
   "2": "b"
   "3": "a"
   "4": "b"

how I can achieve like this:
output:
   "1": "a",
   "2": "b",
   "3": "a",
   "4": "b"

I arleady trying with some rtrim,explode etc but its doesnt work
I arleady trying with rtrim
this doesnt work here is my code:
 while($t= mysql_fetch_array($asd)){
$str = '
   "'.$t['a'].'": "'.$t['b'].'",';
    echo rtrim($str, ",");

A: From what i see is that you are trying to generate a json object, this is not the way to do that.
$data = [];
while (($t = mysql_fetch_array($asd))) {
    $data[$t['a']] = $t['b'];
}

echo json_decode($data);

This will output a json string in the format you are trying to generate.

Sidenote 1:
The reason your rtrim in your code is not working is because you rtrim every line in the while loop, not the last line. But since you use $rest = you are also overwriting the value of $rest in every iteration.

Sidenote 2:
What @jeroen is saying in the comments, do not use mysql_fetch_array, these methods have been deprecated for some time. Look for PDO, mysqli or use a php framework with a proper ORM.

A: Besides rtrim you can use substr() to remove the last character:
while ($something) {
    //construct $str
}
$str = substr($str, 0, -1);

A: You have to do on single string, but right now you are doing it on every string instance in while loop,
$str = '';
while($t= mysql_fetch_array($asd)){
   $str .= '
   "'.$t['a'].'": "'.$t['b'].'",';

}

$str = rtrim($str,",");

Give it a try, this will help.

A: use php rtrim() function to remove the , from the right. The rtrim() function removes whitespace or other predefined characters from the right side of a string.
echo rtrim($rest,",");//remove all the , from right

or, use substr() function of php to remove the last character
echo substr($rest,0,strlen($rest)-1);// remove the last character only

A: try this
$rest = '';
while($t= mysql_fetch_array($asd)){
  $rest .= ' "'.$t['a'].'": "'.$t['b'].'",';
}

$rest = rtrim($rest,",");
echo $rest;

A: Just to throw in an alternative solution:
You could not attach the trailing comma in the first place instead of trimming it afterwards.
Let's assume you have the number of results in $num_rows, then you could do:
$i = 1;
while($t = mysql_fetch_array($asd)) {
    $rest = '"' . $t['a'] . '": "' . $t['b'] . (($i==$num_rows) ? '"' : '",');
    ++$i;
}
echo $rest;

Of course, note what some other answers pointed out: your echo was in the loop, but should stand outside of the loop.
Please also note that you are using the deprecated mysql extension; you should use mysqli instead. See the note in the PHP docs:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.


text:
Q: Opposite of FOR (loop) I got the command:
for /f "delims=// tokens=2,4,6" %%a in (memod.txt) do @echo %%a %%b %%c

Which work as it shall.
But i need one which does not go through every single line of text, but through a single specific line.
Thank you!

A: for /f "skip=N delims=// tokens=2,4,6" %%a in (memod.txt) do @echo %%a %%b %%c & goto break
:break

The skip=N option skips over the first N lines; after processing the line N+1 the goto break the processing of next lines.

A: Since you don't reveal precisely how you want to select the "specific line" it's difficult to come up with an answer, HOWEVER:
"delims=// does NOT select // as your separator as you appear to expect, but selects / and .
From another question, it appears that your data line contains "//" and the FOR..delims... syntax regards successive delimiters as one, so it may APPEAR to work - but it would also "work" on a line like this/is/not/a/target/line/at/all or neither///is///this///a///target///line
Perhaps a structure like
for /f "tokens=2,4,6delims=/" %%a in (
 'type memod.txt^|findstr /r ".*//.*//.*" '
  ) do (
 echo %%a %%b %%c&goto skipfor
)
:skipfor

or
for /f "tokens=2,4,6delims=/" %%a in (
 'type memod.txt^|findstr /r ".*//.*//.*" ^|findstr /v "///" '
  ) do (
 echo %%a %%b %%c&goto skipfor
)
:skipfor

may suit.


text:
Q: Can't drag back elements on empty dom element with double sortable I am starting with jquery sortable but I am having some problems understanding how it works specially when it comes to sort more than 2 different items.
Here's what I have:
http://jsbin.com/ElImEPU/2/
As you can see there I want to create 2 different sorts, one for the outter <ul>'s containing another group of <ul> and another sortable for the inner <li>'s so that I can order elements between the same category.
Problem comes when I drag the last element out of one <ul>. For some reason I can't drag back any other element so this last <ul> remains unusable.
I have read the documentation and in theory it's possible to accomplish this by adding a "connectWith" parameter but seems that I am not using it properly.
Thanks!

A: You should set a default height on the UL elements that are sortabe (i.e. min-height:5px;).
The error is occuring because when the UL is empty it has a height of 0px, by setting the default you ensure it has at least some height.
.ui-sortable {
    min-height:5px;
}

Example JSFiddle


text:
Q: How to use an AWS federated token with AWS iOS SDK 2.0 I've checked the AWS docs, and everything there points to Cognito, can't find how to just use an AccessKeyId and a SecretAccessKey.
All user management and authentication takes place on the server.  There's a long access policy that the server determines based on specific user permissions, and then the server generates a temporary FederationToken with that policy and passes that to the iOS app to use.
Does anyone have a code sample of how to use that passed Federated user in iOS to upload an item to s3?
Thanks

A: You need to implement your credentials provider by conforming to AWSCredentialsProvider. Take a look at the implementations of AWSWebIdentityCredentialsProvider and AWSCognitoCredentialsProvider as examples. This credentials provider should:

*

*Retrieve the access key, secret key, and session key from your server.

*Persist them locally until they expire.

*Return the credentials when requested.

*Re-retrieve them from your server if they are expired.

*Calling - refresh also should initiate the credentials refreshing process.


text:
Q: SQLite3-File: grep: "binary file matches" - how do I get the text from BLOB? I have a .db-file which is a sqlite3-file. When I type
grep -iR "textToSearch" *

I get the result
Binary file Cache.db matches

But when I look into the file (e.g. with Navicat), I only see BLOBs. How do I get the clear text to see what surrounds "textToSearch"?

A: SELECT CAST(MyColumn AS TEXT) FROM MyTable WHERE MyColumn LIKE '%textToSearch%'

A: Just in case: grep -a works too.
From the help:
 -a, --text                equivalent to --binary-files=text


text:
Q: Can you write to Firebase when successfully created new user? I am having a problem storing extra information about the newly created user
myFirebaseRef.createUser(email, pass, new Firebase.ValueResultHandler<Map<String, Object>>() {

@Override
public void onSuccess(Map<String, Object> result)
{
myFirebaseRef.child("Users").child(result.get("uid")).setValue(screenname);
}
});

Is it allowed to write in onSuccess to Firebase?
UPDATE
I have the following rule
"Users" :{
  "$user_id" :{
  ".read": true,
  ".write": "$user_id==auth.uid"
  }
}

UPDATE 2
The problem is with the rule, as the auth.uid is not available untill the user is logged in using the authWithPassword method. So in my case permission is denied.
But how can I limited the write to the location only to the user creating it if they are not logged in yet?

A: You have two actions going on:

*

*create a user

*save the user's data to the database

You have an onSuccess() handler for #1, but not for #2. What you need to do is add a completion listener:
myFirebaseRef
  .child("Users")
  .child(result.get("uid"))
  .setValue(screenname, new Firebase.CompletionListener() {
    @Override
    public void onComplete(FirebaseError firebaseError, Firebase firebase) {
        if (firebaseError != null) {
            System.out.println("Data could not be saved. " + firebaseError.getMessage());
        } else {
            System.out.println("Data saved successfully.");
        }
    }
});


text:
Q: Match element with specific element not working JList ActionListener I'm working on a program that takes an array of contacts and I'm trying to return an integer of how many people are online. I already have a button called refresh that is implemented. I press the "refresh" button on a JFrame and it will refresh the JLabel onlineCountNum which is a empty string at first. After pressing refresh, it shows up 1 to include the user that was online. However, when I log in another user and pressed the refresh button, it doesn't increment but stays at 1 for that user. The JList listContacts has elements with either the name or name(Online). I'm trying to count how many of those have name(Online). If the user is the only one on the server, it should show 1 as the result. If there are two people on the server, it should show 2 for both people and both would see another person as name(Online) on a pane.
private JLabel onlineCountNum;     //label gets refreshed by button
private JLabel onlineCountText;    //"Online Count: " label
private JButton onlineCountUpdate; //refresh button

onlineCountText = new JLabel("Online Count: ");
onlineCountNum = new JLabel("ERROR");
onlineCountUpdate = new JButton("Refresh");
onlineCountNum.setText("");

onlineCountUpdate.addActionListener(new MyButtonListener6());

class MyButtonListener6 implements ActionListener{
    public void actionPerformed(ActionEvent e){
        int count = 1;
        ListModel list = listContacts.getModel();
        for(int i = 0; i < list.getSize(); i++){
            if(list.getElementAt(i).equals(list.getElementAt(i)+"(Online)")){ //possible source of error
                count++;
            }
        }
        onlineCountNum.setText(String.valueOf(count));
    }

}

A: if(list.getElementAt(i).equals(list.getElementAt(i)+"(Online)"))

Yes, this is the source of error...
Now, suppose:
list.getElementAt(i) == "someName(Online)"

What you check for, in the if statement, is:
list.getElementAt(i) == list.getElementAt(i)+"(Online)"

Which is like checking:
"someName(Online)" == "someName(Online)(Online)"

So it will always return false.

What you have to do is:
if(list.getElementAt(i).endsWith("(Online)"))


text:
Q: Why memory is not increasing?Has memory allocated physically? I have tested the code in Xcode 10.3
- (void)loopObjectMalloc {
    while (1) {
        NSObject *obj = [[NSObject alloc] init];
    }
}

I expect the OOM happened, but memory not increased. Is the alloc function not memset to the physical memory ?

A: By default Automatic Reference Counting (ARC) is turned on. So obj will be released at the end of each loop and make memory not be increased.
obj doesn't need to wait for every loops finished.
- (void)loopObjectMalloc {
    while (1) {
        // At the beginning of each loop, `obj` is created.
        NSObject *obj = [[NSObject alloc] init];
        // End of the loop, obj is released due to out of scope.
    }
    // End of function.
}

There is no need autorelease pool to release your object. release will be inserted to your code at compile time automatically.

retain, release, retainCount, autorelease or dealloc cannot be sent to objects. Instead, the compiler inserts these messages at compile time automatically, including [super dealloc] when dealloc is overridden.

https://en.wikipedia.org/wiki/Automatic_Reference_Counting#Objective-C
Note: If you want to see OOM, turn off ARC.

A: You can use use bridging functions to take ownership from ARC:
- (void)loopObjectMalloc {
    while (1) {
        CFTypeRef obj = CFBridgingRetain([[NSObject alloc] init]);
    }
}


text:
Q: How can I pass the fill color of marker as a parameter I have a marker acting as the pointer end of a line to make an arrow:
<marker
  id="triangle"
  viewBox="0 0 4 4"
  refX="10"
  refY="5"
  markerUnits="strokeWidth"
  markerWidth="10"
  markerHeight="10"
  orient="auto"
>
  <path d="M 0 0 L 10 5 L 0 10 z" fill=TO HERE />
</marker>

I am calling it like so from the line
<line
  x1={source.x}
  y1={source.y}
  x2={target.x}
  y2={target.y}
  stroke={
    type === "A" ? "#fff"
    : type === "B" ? "#000"
  } // color of line
  marker-end="url(#triangle)" CALLING IT FROM HERE
/>

How can I pass the fill the marker should be from the line based on the color of line? Can I do something like url(#triangle("fff")) or something like that?
The line is the link component from https://airbnb.io/visx/network .
marker is svg, https://developer.mozilla.org/en-US/docs/Web/SVG/Element/marker