text:
Q: Ruby - How to find out all dependencies of a given Gem in a .rb file? How can I find out all dependencies of a given Gem in a .rb file
without having to rely on system() or similar external calls?
Consider this project:
https://rubygems.org/gems/diamond_shell
It has about 20 - 25 dependencies.
I need to traverse all dependencies, on all the linked
dependencies too, and populate an array with all of them.
Edit: Thanks for the answers.

A: You can yank the code out of lib/rubygems/commands/dependency_command.rb. Here's a simple method I made.
require 'rubygems/commands/dependency_command'

def get_dependencies name, local = true
  cmd = Gem::Commands::DependencyCommand.new

  dependency = cmd.gem_dependency name, nil, nil

  specs =
  if local
    dependency.matching_specs.uniq.sort
  else
    cmd.fetch_remote_specs(dependency).uniq.sort
  end

  dependencies = []
  specs.each do |spec|
    dependencies.concat spec.dependencies.sort_by { |dep| dep.name }.map { |dep| [dep.name, dep.requirement] }
  end
  dependencies
end

puts get_dependencies('diamond_shell', false)

A: If you happen to be using Bundler for ruby gem management (http://bundler.io), the bundle install run generates a Gemfile.lock manifest file with all project gems and their dependencies. An example is below:
sunspot (2.0.0)
  pr_geohash (~> 1.0)
  rsolr (~> 1.0.7)
sunspot_rails (2.0.0)
  nokogiri
  sunspot (= 2.0.0)
teaspoon (0.7.8)
  phantomjs (>= 1.8.1.1)
  railties (>= 3.2.5, < 5)

This file can be easily parsed to get your dependency tree.


text:
Q: Battery Menu Bar doesn't show Time Remaining Kinda a unique issue here I haven't been able to find the solution to on Google.  As you can see in the screenshot below, my battery menu doesn't give me time remaining on Battery.  Not even System Preferences gives me it.

Has this happened to anyone else? I'd love to re-enable it.  If it's important, I'm running macOS Sierra.

A: I can think of several failures to cause that, but let's rule out the obvious.
Open terminal.app and type:
pmset -g pslog

The log will show what the power management subsystem is seeing from the SMC. After trying to connect power, disconnect power and seeing charge for 10 minutes and then off charge for 10 minutes, you should have a good understanding of what is or what isn't working.
At that point, try resetting your SMC one time. Make a note of the information as if that doesn't fix things it's likely a hardware service situation.

*

*https://support.apple.com/en-us/HT201295 - How to reset the SMC

A: Believe it or not, this was actually an intentional change as of macOS 10.12.2.  Likely in response to the complaints about short/erratic battery life in the newer Touch Bar-equipped models of MacBook Pro, Apple simply removed that information from the menu.  It is, however, still accessible from the Energy tab of Activity Monitor.
From this page:

Apple tells us that according to all its testing and user data, the batteries in the new MacBook Pros are performing normally—there's no bug that's sapping your battery, and your real-world battery life is still going to be influenced strongly by your workload. The only battery life-related fix in 10.12.2 is the removal of the "time remaining" estimate from the operating system. Apple says this is because modern components switch power states so frequently and quickly that it's hard to correctly estimate remaining battery life based on current activity.

A: I made a really simple little app that displays the remaining time in the mac menubar.
https://github.com/funkyremi/macos-battery-remaining-menubar

A: The battery time remaining was intentionally removed by Apple due to the inaccuracy of the estimation, which is highly dependent on the laptop workload. Nonetheless, there are some free mac os apps, such as TLOB, that bring this feature back.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve and display individual object from array Javascipt/React Suppose I have an array:
{
    "data": [
        {
            "id": 9,
            "body": "This is the first body of text,
            "availability": "internal",
            "title": "Test",
            "posted_by": "Test"
        },
        {
            "id": 10,
            "body": "This is the second body of text",
            "availability": "internal",
            "title": "TEST2",
            "posted_by": "TEST2"
        },
}

My aim is to be able to print a specific "title" or "body" in my React app. Previously I had the data in JSON where I could simply use something like data.title[0] which would be Test.
Now I pull data using the following code:
componentDidMount() {
    axios
      .get(
        "API_KEY"
      )
      .then((res) => {
        let data = res.data
        this.setState({ data, loading: false });
        console.log(data)
      });
  }

  render() {
    if (this.state.loading) {
      return <Loader />
    }

    else
    return (
       this.state.data.data.map((item) => (
          <>
          <marquee direction="left" behaviour="scroll">
            <p key={item.id}>{item.body} </p>
            </marquee>
          </>
        ))

And I can't find a way to print specific "title" or "body" values, only every output in the array.
Currently my only idea is to use .slice() to manipulate the data the way I want, but this seems like a dirty way of fixing my issue.
Any advice/guidance greatly appreciated, thanks!

A: Unpacking fields from objects passed as a function parameter can do this.
const user = {
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe'
  }
};

function userId({id}) {
return id;
 }

function whois({displayName, fullName: {firstName: name}}) {
return `${displayName} is ${name}`;
 }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment


text:
Q: I've written this code to find duplicates and it works fine: SELECT Cust_FirstName, Cust_LastName,Cust_PhoneNumber,Cust_Email
FROM tbl_Customer
GROUP BY Cust_FirstName,Cust_LastName,Cust_PhoneNumber,Cust_Email
HAVING COUNT(*) > 1

The problem is, it's returning just one of the duplicate rows. Is it possible to return all the duplicate rows? I'm guessing it may have something to do with the 'GROUP BY' but

A: Maybe something like this
WITH g AS (
    SELECT Cust_FirstName, Cust_LastName,Cust_PhoneNumber,Cust_Email
    FROM tbl_Customer
    GROUP BY Cust_FirstName,Cust_LastName,Cust_PhoneNumber,Cust_Email
    HAVING COUNT(*) > 1
)
SELECT c.*
FROM tbl_Customer c
INNER JOIN g
ON c.Cust_FirstName = g.CustFirstName
AND c.Cust_LastName = g.Cust_LastName
AND c.Cust_PhoneNumber = g.Cust_PhoneNumber
AND c.Cust_Email = g.Cust_Email

A: I recommend using window functions:
SELECT c.*
FROM (SELECT c.*, COUNT(*) OVER (PARTITION BY Cust_FirstName, Cust_LastName, Cust_PhoneNumber, Cust_Email) as cnt
      FROM tbl_Customer c
     ) c
WHERE cnt > 1
ORDER BY cnt DESC,
         Cust_FirstName, Cust_LastName, Cust_PhoneNumber, Cust_Email;

Not only should this have better performance than a solution using GROUP BY/JOIN.  It also handles NULL values, so you will see duplicates where there are NULLs.  Of course, you can control the NULLs using a WHERE clause if you actually want to filter them out.


text:
Q: Laravel: how to add where clause using query builder? I have this query, made using Laravel query builder:
$rows = DB::table('elements')->where('type', 1);

That corresponds to: "SELECT * from elements WHERE type=1"
Now, in some cases I need to add a second Where to create a query like this:
SELECT * from elements WHERE type=1 AND lang='EN'

Using classic php I'd do something like:
$sql = 'SELECT * from elements WHERE type=1';

if($var==true) $sql .= " AND lang='EN'";

How can I do that using Laravel Query Builder?
Thank you.

A: You may try something like this
$query =  DB::table('elements');
$query->where('some_field', 'some_value');

// Conditionally add another where
if($type) $query->where('type', 1);

// Conditionally add another where
if($lang) $query->where('lang', 'EN');

$rows = $query->get();

Also, check this answer.

A: $userId = Auth::id();
$data['user_list'] =DB::table('users')->
select('name')->
where('id','!=',$userId)->
where('is_admin','!=','1')->
get();

like that you use multiple where clause :)


text:
Q: fixed div overlaps other div in container I have two divs in a wrapper. One floats left at 20% width, one floats right at 80% width. Both have a max width of 2000px with auto margins in order to center the content. The problem I'm having is that at a larger width, the divs begin to overlap and I cannot figure out how to get them side by side regardless of the width.
Here is my html:

Here is my css
body
    {
    background-color: #3F3F3F;
    }

.wrapper
    {
    width: 100%;
    height: auto;
    max-width: 2000px;
    margin-left:auto;
    margin-right:auto;
    }

.container
    {
    width: 20%;
    background-color:#F6F6F6;
    height: 200px;
    float: left;
    position: fixed;
    max-width: 2000px;
    margin-left:auto;
    margin-right:auto;
    }

    .slider {
        width: 80%;
        height: 2000px;
        float: right;
        position: relative;
        background-color: #8A0002;
        opacity: .2;
        max-width: 2000px;
        margin-left:auto;
        margin-right:auto;
        }

I'm a student and really appreciate any help!!!

A: Use position: relative in .container.
With position: fixed it seems to calculate the container as the 20% of the width of the wrapper + its margins.

A: Update
please ignore this answer I kept it for the comment.

You'll need to clear your floats. You can read more here.
This is a JSFiddle sample of one way to do it.
or you can simple add an element inside your wrapper and clear that one.
.clearfix:before,
.clearfix:after {
 content: "";
 display: table;
}

.clearfix:after {
 clear: both;
}

.clearfix {
 zoom: 1; /* ie 6/7 */
}

add this do your CSS and and change your wrapper to

Reference : Sitepoint


text:
Q: Diffusion to capture on the surface of a cylinder wall
Hi all, is it correct to use equation 10.3.4 on the above textbook for the flux of particles onto a surface of the cylinder wall (radius a, length L)? If yes, then the rate of collisions of particles to the wall will be the equation below? Thanks!
$$ j=JA=(\frac{DC_0}{a})*2{\pi}*a*L=2{\pi}DLC_0 $$

A: For the cylindrical geometry we get (steady state):
$$\frac{1}{r} C_r\left(r C_r\right)=0$$
For $r\neq 0$ and assume $L\gg a$ (cylinder length), so we can neglect diffusion on the end-caps:
$$C_r+rC_{rr}=0$$
Solution:
$$C(r)=c_1\ln r+c_2$$
First boundary condition:
$$C(a)=0$$
$$0=c_1\ln a+c_2$$
Second boundary condition:
$$J(a) = -D \left. \dfrac{\partial C}{\partial r} \right|_{r=a} = - \dfrac{DC_0}{a}$$
$$-Dc_1\frac{1}{a}=- \dfrac{DC_0}{a}$$
$$\Rightarrow c_1=C_0$$
$$\Rightarrow c_2=-c_1\ln a$$
$$C(r)=C_0\ln r-C_0\ln a=C_0\ln \frac{r}{a}$$
So that:
$$\boxed{j=JA=2 \pi D La}$$

A:
Is there a problem with the 2nd boundary condition?


text:
Q: Need Help With Implementing Simple Stuff with PHP and MYSQL Here is my code -
<?php

$u = $_SESSION['username'];
while($fetchy = mysqli_fetch_array($allusers))
{

mysqli_select_db($connect,"button");
$select = "select * from button where sessionusername='$u' AND response = 'approve'";
$query = mysqli_query($connect,$select) or die('Oops, Could not connect');
$result= mysqli_fetch_array($query);
$email = mysqli_real_escape_string($connect,trim($result['onuser']));
echo $email;

if($email){
    mysqli_select_db($connect,"users");
    $select_name = "select name, icon from profile where email = '$email'";
$query_2 = mysqli_query($connect,$select_name) or die('Oops, Could not connect. Sorry.');
$results= mysqli_fetch_array($query_2);
$name = mysqli_real_escape_string($connect,trim($results['name']));
$icon = mysqli_real_escape_string($connect,trim($results['icon']));
echo $name;
}

}
NOw, there are two reponses in db. So, two names are getting echoed, but they both are SAME. Why so? Eg
DB - NAMEs - Apple and Orange.
Displayed - Apple Apple.
Database example -
SESSIONUSERNAME      OnUSer

s@s.com              apple
s@s.com              orange

EDITED
Using @endophage's method -
AppleOrange and AppleOrange.

A: As your loop stands now, $u will always be the same, so $select will always have the same value, and so will $email, and so will $select_name, so it is no surprise that the same record keeps coming back.
Edit
If the $select_name query returns multiple results, then you need to loop through the results with a while loop like the other queries.

A: Try this, you had your while loop in the wrong place:
<?php

$u = $_SESSION['username'];

mysqli_select_db($connect,"button");
$select = "select * from button where sessionusername='$u' AND response = 'approve'";
$query = mysqli_query($connect,$select) or die('Oops, Could not connect');
while($result = mysqli_fetch_array($query))
{
  $email = mysqli_real_escape_string($connect,trim($result['onuser']));
  echo $email;

  if($email){
      mysqli_select_db($connect,"users");
      $select_name = "select name, icon from profile where email = '$email'";
      $query_2 = mysqli_query($connect,$select_name) or die('Oops, Could not connect. Sorry.');
      $results= mysqli_fetch_array($query_2);
      $name = mysqli_real_escape_string($connect,trim($results['name']));
      $icon = mysqli_real_escape_string($connect,trim($results['icon']));
      echo $name;
  }
}


text:
Q: Delayed scheduling over an hour in Redis I have a requirement in which I have to do delayed scheduling in Redis. The delay can be in hours. As discussed in this answer one way of achieving this as below:-

*

*Add jobs to a sorted set

*Dispatcher thread which checks sorted sets every N seconds e.g -  ZRANGEBYSCORE jobs -inf, <current unix timestamp>

*Whenever some jobs are available move it to main job list where main job workers are blpop'ing.

*Delete the jobs from sorted set.

Can some one suggest some ways how can I modify the above approach to handle the below case:-
I can't afford to lose message or give duplicate jobs to main worker thread. In the above approach if the dispatcher thread dies after reading the message from sorted set, writing to main job list but before deleting the message from sorted set. Then the message will be delivered twice to the main job list?
One way I can think of is the dispatcher thread will write to an intermediate list rather than to main list. One more thread will keep on checking the intermediate list in every N seconds. Whenever some job is available move it to the main list by doing BRPOPLPUSH.
Can some one suggest some other better and optimal way?

A: I don't try it but I think you can use a Lua script to transfer job from sorted set to main job list and delete it from the sorted set. According to the documentation on transaction :

A Redis script is transactional by definition, so everything you can do with a Redis transaction, you can also do with a script, and usually the script will be both simpler and faster

And

All the commands in a transaction are serialized and executed sequentially. It can never happen that a request issued by another client is served in the middle of the execution of a Redis transaction. This guarantees that the commands are executed as a single isolated operation.
  Either all of the commands or none are processed, so a Redis transaction is also atomic.


text:
Q: Build list of tuples from simple list This is what I am supposed to do :
Write a function to get a list of values L from the user and build from it a list of tuples in the form [(a1,b1),..(an,bn)] where ai are each of the values of the original list and bi represent its position in the list.
Example:
For L=[3,2,-1,7,3,5] the function should build and return [(3,1),(2,2),(-1,3),(7,4), (3,5),(5,6)]
This is my code:
a=input("Enter values separated by comas: ")
L=eval(a)
print(L)

A: Use enumerate and list comprehension:
>>> L = [3, 2, -1, 7, 3, 5]
>>> [(x, i) for i, x in enumerate(L, 1)]
[(3, 1), (2, 2), (-1, 3), (7, 4), (3, 5), (5, 6)]

Help on enumerate:
>>> help(enumerate)
Help on class enumerate in module __builtin__:

class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument.
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...


text:
Q: In the pygame module , on pressing the right key, only the first sprite in the list is being loaded In the pygame module , on pressing the right key, only the first sprite in the list is being loaded
WR=[pygame.image.load('R2.png'),pygame.image.load('R3.png'),pygame.image.load('R4.png'),pygame.image.load('R5.png'),pygame.image.load('R6.png'),pygame.image.load('R2.png')]
char=pygame.image.load('char.png')

def redrawGameWindow():
    global wc

    screen.blit(BG,(0,0))
    if wc+1>=27:
        wc=0

    if right:
        screen.blit(WR[wc//3],(x,y))

    else:
        screen.blit(char,(x,y))

A: You forgot to increment wc:
wc += 1

However, WR is a list with 6 elements (Surfaces), but the maximum subscription index is 9 (27/3 == 9). This will cause "IndexError: list index out of range" error.
Make sure the index is in the range of the list. Use len() to get the length of the list and restart the animation (wc = 0) when the subscription index exceeds the length of the list:
def redrawGameWindow():
    global wc

    wc += 1
    if wc // 3 >= len(WR):
        wc = 0

    screen.blit(BG, (0,0))
    if right:
        screen.blit(WR[wc // 3 ], (x, y))
    else:
        screen.blit(char, (x, y))


text:
Q: Mqtt Paho Client Connection always open i have created mqtt connection suscribeData() as follows to receive data 24/7 from multiple devices
@RequestMapping("/suscribe")
@ResponseBody
public String suscribeData(){

    connOpt= new MqttConnectOptions();
    connOptPublish= new MqttConnectOptions();
    boolean result=false;
    int retry=0;
    while(!result){
        try{
            result=initializeMqTTParameters(retry);
            retry++;
            if(!result){
                Thread.sleep(1000);
            }

        }catch(Exception ex){

        }
        if(retry>10){
            return "mqtterror";
        }

    }
        suscribeReceivedData("DATA/#",2);
        Calendar cal=TimeZoneJu.getCalenderInstance();
        ModemOnlineStatus status=new ModemOnlineStatus();
        status.setActiondate(cal.getTime());
        status.setActiontime(cal.getTime());
        status.setModemid("mqttreceive");
        status.setRemark("online");
        status.setStatus(true);
        try{

            service.checkAndInsertModemStatus(true, status);
        }catch(Exception ex1){

        }
        return "ok";
}

checkAndInsertModemStatus() function is used to save the online offline state of connection i check the connection from another url with cronjobs.
and following is my initializeMqTTParameters
public boolean initializeMqTTParameters(int retry){
        String clientID = M2MIO_THING;
        connOpt = new MqttConnectOptions();

        connOpt.setCleanSession(false);
        connOpt.setUserName(M2MIO_USERNAME);
        connOpt.setPassword(M2MIO_PASSWORD_MD5.toCharArray());
        connOpt.setWill("WILL/mqttreceive", "mqttreceive:disconnected".getBytes(), 2, true);
        try {

            if(retry%2==0){
                MQTTReceive.myClient = new MqttClient(BROKER_URL, "mqtt_virtual_received_sus_1");
            }else{
                MQTTReceive.myClient = new MqttClient(BROKER_URL, "mqtt_virtual_received_sus_2");
            }

            MQTTReceive.myClient.setCallback(this);
            MQTTReceive.myClient.connect(connOpt);

        } catch (MqttException e) {
            System.out.println(e.getMessage());
            return false;
        }
        return true;
    }

on connectionLost i am trying update status in database and try reconnect
@Override
    public void connectionLost(Throwable ex) {
        System.out.println("Mqtt Received Connection Lost"+ex.getMessage());
        Calendar cal=TimeZoneJu.getCalenderInstance();
        ModemOnlineStatus status=new ModemOnlineStatus();
        status.setActiondate(cal.getTime());
        status.setActiontime(cal.getTime());
        status.setModemid("mqttreceive");
        status.setRemark("offline");
        status.setStatus(false);
        try{

        service.updateModemStatus(false, status);
    }catch(Exception ex1){

    }

    suscribeData();
}

and from the above code i got my connections were online but i stopped receving data on subscribed topics so another method i tried that i am checking connection status from another function from database like i set the connection online when i connect and offline on connectionLost and i can call to connect(suscribeData()) but it leaves me with too many open files in tomcat within few days how can i make sure previous open files should close
like System.exit(1) on connectionLost() so that current process will close and i will reconnect after checking the status
or please suggest me if there is any other logic i can use to maintain my connections

A: Your catch block does nothing in method connectionLost.. it should do something like this:
 catch (Exception e)
         {
              e.printStackTrace();
              System.exit(1);
          }

You should also disconnect your MQTT client whenever not required..i.e processing over:
myClient.disconnect();


text:
Q: If statement using php and advances custom fields in wordpress - hide empty fields I have an and if statement for a button.
If both advanced custom fields are present I want it to show the button and if not I want it to hide but I am struggling here.
I have looked at this page:
https://www.advancedcustomfields.com/resources/hiding-empty-fields/
Here is my code:
<?php if( get_field('button_link') && get_field('button_text') ): ?>
    <a href="<?php the_field('button_link');  ?>" class="btn third-btn mx-auto">
    <?php the_field('button_text');?>

<?php endif; ?>

Anyone got a suggestion please?
Cheers :)

A: I am not an ACF expert but looking at the get_field() function description here https://www.advancedcustomfields.com/resources/get_field/ it looks like the function will never return a boolean as mentioned on the Description and I quote:

Returns the value of the specified field

Since it does not return a boolean value, you can't assure get_field( 'something' ) && get_field( 'something2' ) will be the correct boolean. There are certain values that the if statement interpret as boolean true or false. For example null and 0 are interpreted as false, but -1 interpreted as true. I would recommend to do a
var_dump( get_field('button_link') )

to explore the output. Also, according to https://www.advancedcustomfields.com/resources/get_field/ under 'Check if value exists' you can check if one value exists, so this might work:
<?php if ( get_field( 'button_link' ) ) : ?>
    <?php if ( get_field( 'button_text' ) ) : ?>
        <a href="<?php the_field( 'button_link' ) ?>" class="btn third-btn mx-auto">
            <?php the_field( 'button_text' ) ?>

    <?php endif ?>
<?php endif ?>

It is like a nested AND without using the && operator. If this does not work we need more information about what you get from:
var_dump( get_field( 'button_link' ) );
var_dump( get_field( 'button_text' ) );


text:
Q: Show that the element $z=i \cos \frac{\pi}{3}+\sin \frac{\pi}{3} = i( \cos \frac{\pi}{3} - i \sin \frac{\pi}{3})$ belongs to $U_{12}$ Show that the element $\displaystyle z=i \cos \frac{\pi}{3}+\sin \frac{\pi}{3} = i( \cos \frac{\pi}{3} - i \sin \frac{\pi}{3})$ belongs to U12
What I don't understand:

*

*In what way $i \cos \frac{\pi}{3} + \sin \frac{\pi}{3}$ is different from $i(\cos \frac{\pi}{3} - i \sin \frac{\pi}{3})$ corresponding to the polar solutions of U12

2.U12 has 12 polar elements and from Cayley's table we see there are 4 elements, how this is different?
The 4 elements are the generators and others are not (primes), how's this is different for the polar elements?
Thanks for the help and tips

A: I might be misunderstanding your question, but here goes nothing!
It seems like we want to prove that $z^{12} = 1$. Now
$$ z = i(\cos\frac{\pi}{3} - i\sin\frac{\pi}{3}) = i(\cos(-\frac{\pi}{3}) + i\sin(-\frac{\pi}{3})) = ie^{-i\frac{\pi}{3}} = ie^{-i\frac{2\pi}{6}} $$
$$z^6 = i^6(e^{-i\frac{2\pi}{6}})^6 = -1$$
$$z^{12} = (z^6)^2 = (-1)^2 = 1$$
For your second question, notice that $z$ is the $12$-th root of $1$. If another element $\alpha$ satisfies $\alpha^{12} = 1$, see if you can figure out how $z$ relates to $\alpha$


text:
Q: ubuntu 20.04 - wireless not working for intel AX1650i (lenovo thinkpad) Kernel version is 5.9.12-050912-generic Below two images that I think show that some firmware/driver is missing, but couldn't manage to get it to work.

Also there are no blocks:
nico@nico:/usr/lib/firmware$ rfkill list all
0: ideapad_wlan: Wireless LAN
    Soft blocked: no
    Hard blocked: no

Does somebody knows how to fix this?
[EDIT]
nico@nico:/usr/lib/firmware$ lspci -nnk | grep -iA3 net
lspci: Unable to load libkmod resources: error -12
00:14.3 Network controller [0280]: Intel Corporation Killer Wi-Fi 6 AX1650i 160MHz Wireless Network Adapter (201NGW) [8086:34f0] (rev 30)
    Subsystem: Intel Corporation Killer Wi-Fi 6 AX1650i 160MHz Wireless Network Adapter (201NGW) [8086:0000]
00:15.0 Serial bus controller [0c80]: Intel Corporation Ice Lake-LP Serial IO I2C Controller #0 [8086:34e8] (rev 30)
    Subsystem: Lenovo Ice Lake-LP Serial IO I2C Controller [17aa:3852]
    Kernel driver in use: intel-lpss
--
01:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 15)
    Subsystem: Lenovo RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [17aa:3852]
    Kernel driver in use: r8169
02:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS522A PCI Express Card Reader [10ec:522a] (rev 01)
    Subsystem: Lenovo RTS522A PCI Express Card Reader [17aa:3852]

[EDIT 2]
This command has  a longer output, which is just the same but with a different code before ucode
sudo modprobe iwlwifi && dmesg | grep iwl
[    9.032170] iwlwifi 0000:00:14.3: Direct firmware load for (efault)3.ucode failed with error -2
[    9.032177] iwlwifi 0000:00:14.3: Direct firmware load for (efault)2.ucode failed with error -2
[    9.032184] iwlwifi 0000:00:14.3: Direct firmware load for (efault)1.ucode failed with error -2
[    9.032192] iwlwifi 0000:00:14.3: Direct firmware load for (efault)0.ucode failed with error -2
[    9.032192] iwlwifi 0000:00:14.3: no suitable firmware found!
[    9.032214] iwlwifi 0000:00:14.3: minimum version required: (efault)0
[    9.032235] iwlwifi 0000:00:14.3: maximum version supported: (efault)128
[    9.032255] iwlwifi 0000:00:14.3: check git://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git


text:
Q: How to keep a long-running HTTP connection alive in Dropwizard/Jersey? I have a simple rest endpoint that is searching for a message in a Kafka topic.  Depending on when/if this message is found, this process could take a couple minutes.  When I call this endpoint via Swagger I end up receiving a 504 - Server Timeout back.  How can I keep this connection alive so the client doesn't receive a timeout?

A: Dropwizard will let you configure the idleTimeout (defaults to 30 seconds), see configuration reference
But I must warn you this is a dangerous path with issues like:

*

*Draining the connection pool

*Network issues that will terminate the connections

*Middlewares (like load balancers) that will terminate the connections

If your process needs more time then there are some solutions like:
1. Websockets (notify the client when the operation completed)
2. Long polling (periodically poll the server for completion result)


text:
Q: How To Split Pipe-Delimited Column and insert each value into new table Once? I have an old database with a gazillion records (more or less) that have a single tags column (with tags being pipe-delimited) that looks like so:
    Breakfast
    Breakfast|Brunch|Buffet|Burger|Cakes|Crepes|Deli|Dessert|Dim Sum|Fast Food|Fine Wine|Spirits|Kebab|Noodles|Organic|Pizza|Salad|Seafood|Steakhouse|Sushi|Tapas|Vegetarian
    Breakfast|Brunch|Buffet|Burger|Deli|Dessert|Fast Food|Fine Wine|Spirits|Noodles|Pizza|Salad|Seafood|Steakhouse|Vegetarian
    Breakfast|Brunch|Buffet|Cakes|Crepes|Dessert|Fine Wine|Spirits|Salad|Seafood|Steakhouse|Tapas|Teahouse
    Breakfast|Brunch|Burger|Crepes|Salad
    Breakfast|Brunch|Cakes|Dessert|Dim Sum|Noodles|Pizza|Salad|Seafood|Steakhouse|Vegetarian
    Breakfast|Brunch|Cakes|Dessert|Dim Sum|Noodles|Pizza|Salad|Seafood|Vegetarian
    Breakfast|Brunch|Deli|Dessert|Organic|Salad
    Breakfast|Brunch|Dessert|Dim Sum|Hot Pot|Seafood
    Breakfast|Brunch|Dessert|Dim Sum|Seafood
    Breakfast|Brunch|Dessert|Fine Wine|Spirits|Noodles|Pizza|Salad|Seafood
    Breakfast|Brunch|Dessert|Fine Wine|Spirits|Salad|Vegetarian

Is there a way one could retrieve each tag and insert it into a new table  tag_id | tag_nm using MySQL only?

A: Here is my attempt which uses PHP..., I imagine this could be more efficient with a clever MySQL query.  I've placed the relationship part of it there too.  There's no escaping and error checking.
$rs = mysql_query('SELECT `venue_id`, `tag` FROM `venue` AS a');
while ($row = mysql_fetch_array($rs)) {
    $tag_array = explode('|',$row['tag']);
    $venueid = $row['venue_id'];
    foreach ($tag_array as $tag) {
        $rs2 = mysql_query("SELECT `tag_id` FROM `tag` WHERE tag_nm = '$tag'");
        $tagid = 0;
        while ($row2 = mysql_fetch_array($rs2)) $tagid = $row2['tag_id'];
        if (!$tagid) {
            mysql_execute("INSERT INTO `tag` (`tag_nm`) VALUES ('$tag')");
            $tagid = mysql_insert_id;
        }
        mysql_execute("INSERT INTO `venue_tag_rel` (`venue_id`, `tag_id`) VALUES ($venueid, $tagid)");
    }
}

A: After finding there is no official split function I've solved the issue using only MySQL like so:
1: I created the function strSplit
CREATE FUNCTION strSplit(x varchar(21845), delim varchar(255), pos int) returns varchar(255)
return replace(
replace(
substring_index(x, delim, pos),
substring_index(x, delim, pos - 1),
''
),
delim,
''
);

Second I inserted the new tags into my new table  (real names and collumns changed, to keep it simple)
INSERT IGNORE INTO tag (SELECT null, strSplit(`Tag`,'|',1) AS T FROM `old_venue` GROUP BY T)

Rinse and repeat increasing the pos by one for each collumn (in this case I had a maximum of 8 seperators)
Third to get the relationship
INSERT INTO `venue_tag_rel`
(Select a.`venue_id`, b.`tag_id` from `old_venue` a, `tag` b
     WHERE
     (
     a.`Tag` LIKE CONCAT('%|',b.`tag_nm`)
     OR a.`Tag` LIKE CONCAT(b.`tag_nm`,'|%')
     OR a.`Tag` LIKE CONCAT(CONCAT('%|',b.`tag_nm`),'|%')
     OR  a.`Tag` LIKE b.`tag_nm`
     )
)


text:
Q: layoutinflater Show NullPonterExecption I can try may code by no result
my app install in device but can`t run
it show error in LayoutInflater
public class ViewPagerAdapter extends PagerAdapter {

    private LayoutInflater l;
    public  ViewPagerAdapter(){

    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        l =(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = l.inflate(layouts[position],container,false);
       container.addView(view);
        return view;
    }

    @Override
    public int getCount() {
        return layouts.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View v= (View)object;
        container.removeView(v);
        }
    }
 }

A: Initialise your Inflater using,
  LayoutInflater inflater = getLayoutInflater().from(context);

A: Use LayoutInflater.from(container.getContext()) or container.getContext().getSystemService() to obtain your inflater instance

A: You can access the system services through context like below code
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

You should pass the context to the ViewPagerAdapter through constructor, through which you can access the systemServices to get the inflater.


text:
Q: Style guide to avoid condescension in answers I've had two suggested edits rejected by the author, which attempted to make an answer more accessible by amending its condescending opening paragraph.
The use of words such as "simply", "just", "easy", "ridiculously easy" or, in this case, "amazingly easy" can serve to make the reader embarrassed that they find it more difficult, and annoyed at the inference of superiority, even if that is not the intention of the answerer. This can limit the usefulness and accessibility of an answer because the reader has to first overcome their irritation and possible shame.
Stack Overflow (and other SE sites) wouldn't be needed if folks thought the solution to their problem was "amazingly easy". It seems out of place to use language that suggests users are stupid. Is there a style guide which can be referenced to avoid this unfortunate effect?

A: I don't see anything but upside in these edits. You haven't changed the meanings of the answers. By bringing a different perspective, you've made them accessible to a larger audience, which likely means the authors would have benefited from more upvotes and rep. Most of all, it's great feedback that the authors could use to learn to communicate more effectively.
If they won't use it, I will. Thank you for the lesson in empathy. And please keep it up. We need more people with your skill set in this community.

A: I don't think saying "this is really easy to do once you know it" is patronizing or rude.
Better spend the time fixing actual issues with posts (e.g. grammar, formatting) and leave those alone, especially in answers which were posted many years ago.

A: In most cases - I do believe the intent of the writer (and their style) ought to be respected to a certain level.
I do believe that the seeming contracending tone is really "Yanno, this looks scary until you do it! You can do it! Its easy!" in fewer words. As such, the goal of the author seems to be to point out its no great mystery, and much like my dog, git's bark can be worse than its bite.
In my experience, as someone who basically got thrown head first into git - making a mistake and reverting is scary and pointing out that its not kind of helps the pedagogical goals of answering.
Admittedly, sometimes people are a little precious about their personal writing style (I was, back in the day) but in this case, I really do feel the edit didn't really add to the post at all.
If you had been a high enough rep user to do it yourself, the likely result would have been a reversal of your edit anyway.
There's no style guide. We write as we do, and if you feel there's a broader issue - you comment, or bring it up to meta as you've done. At the same time, its worth also considering picking the edits that do the most good, or remove the most annoyance for the most - technical ones, rather than "feel good" edits of that sort, except in the most egregarious situations (but then you want to flag it when someone is clearly not being nice).

A: What you tried to edit is not condescending to the reader.
The first post, about Git, is encouraging. It says "once you know how", and then goes on to explain how. It promises the reader that she has the ability to accomplish this feat despite the fact that it's "scary". This is the verbiage of someone who wants the person being instructed to succeed and is literally telling her that the thing she wants to do is not as hard as it first appears.
A condescending version would be

Undoing a commit wouldn't be scary if you had any idea what you're doing. It's so easy that it's amazing you don't know how it works.

This is attacking the reader; it is castigating her for her lack of knowledge. The original version recognizes the lack as a natural state that can easily be remedied and then helps to remedy it.
Your second edit is even further out of line. The subject of the sentence "Python makes this ridiculously easy." is not the reader. It's the language. There's nothing to fix here; no person is being talked down to.
Would you really take offense if you were told "Here, use my hammer, it'll make that ridiculously easy" when you asked how to pound a nail? That's exactly what you asked for!


text:
Q: UIView Orientation in UINavigationController in IOS6 I have a UINavigation base app in which I was supporting all orientations for some view controller but not for all using this code

@interface UINavigationController (Autorotation)

*

*(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation;
@end
@implementation UINavigationController (Autorotation)

*(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{

if ([self.visibleViewController isKindOfClass:[MWPhotoBrowser
  class]] || [self.visibleViewController
  isKindOfClass:[ZoomPictureViewController class]]) {
          return YES;
      }
      return  (toInterfaceOrientation == UIInterfaceOrientationPortrait);
  }
  @end

It was working great but not working in IOS6. I have set all four orientations supported in my projects plist file.
Help if anyone has found some work around for.

A: Here is the link for apple documentation Read it :)
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/BasicViewControllers/BasicViewControllers.html
Hope this will help.

A: In ios 6 there are new methods for orientation use these methods in your navigation controller subclass
-(BOOL) shouldAutorotate
{
return YES;
}

-(NSUInteger) supportedInterfaceOrientations{
if ([self.visibleViewController isKindOfClass:[YourClass class]] ||[self.visibleViewController isKindOfClass:[YourClass class]]) {
return UIInterfaceOrientationMaskAll;
}

return UIInterfaceOrientationMaskPortrait;
}


text:
Q: Logging authentication attempts including passwords I'm writing a comprehensive authentication system for an application and I was planning on logging failed authentication attempts in order to implement better security.  I would like to check failed passwords for both brute force and dictionary attacks, however the only method I could think of doing this is by storing the raw password.
I have mixed feelings about doing this.  Although I know that the failed login attempts will be cleared every so often I don't like the idea of raw passwords being stored in a database.  I know I mistype passwords very often which are very similar to my real password, or worse yet I'll type a wrong password for a particular login that is actually an active password for another website I belong to.
It would however be impossible to implement advanced security without storing some raw passwords, so I'm trying to think about the best way to do it.
Here are some possible solutions I have thought of:

*

*Don't store more then 24 hours of login attempts. This isn't really a solution, more of simply limiting the damage if the passwords are compromised.

*Clear a users failed attempts if they are successfully authenticated.

Anyone have any input on this? Is this a good/bad idea? Should I use two-way encryption?

A: This seems like over-engineering. I would just keep track of failed login attempts & after $x amount of failed login attempts, you then block the IP from attempting another login for 1-24hrs or so.
If you're concerned someone is targeting a specific account you can note the number of failed attempts on a specific username & then take appropriate measures, such as limiting failed logins on that username to 2 or 3 per 24hr period on any ip address.
I can think of ways you could try to detect dictionary/brute attacks via comparison, but you're going to have to collect user input and compare it to previous attempts, this could be a security problem if you're storing slightly misspelled legitimate passwords in a database. Plus this is going to take up quite a bit of CPU power to churn through for every login.
The goal should be to make it intensively slow for brute-force attackers, but not annoying or compromising for legitimate users.
Though now that I am thinking on this a bit more, the prevention method could also be a way of denial-of-service by locking users out of being able to login, so take my suggestion with that in mind.

A: Logging raw passwords seems like a really bad idea, as you pointed out yourself.
Could you just log the username, and the times of failed logins, without actually logging the passwords? It would be fairly obvious if there was a bruteforce attack if there were hundreds of log-in attempts within a short space of time. You can also log the IP address.

A: there's a big difference between a user making mistakes and a brute force / dictionary attack: the volume of requests. Don't store failed attempts - you're quite right that the plaintext password should be handled minimally - just look at the pattern of attempts. That should be enough data.
anything else, and your 'advanced security' starts looking like 'advanced attack vector possibilities'.

A: I'm not sure what you mean when you mention storing raw passwords- presumably you only want to store the failed password attempts in plain text to analyze for patterns (dictionary attacks) and volume (brute force).
In my limited experience, you would take the user's inputted password, hash it (with a salt, the same salt used to hash the stored password) and compare with the stored hashed value. If the validation fails (the hashed values are not equal), log the plain text version of the password used for the attempt.
I would advise also implementing locking out of an account after a certain number of failed attempts and possibly having an exponential timeout window for when a login attempt can be tried again. If a user enters a password incorrectly to begin, but then enters a password correctly, you might consider deleting the password captured for the failed login for this particular session.

A: Depending on the authentication protocol you select, e.g., in the case of Kerberos, you may not even have access to the password entered.

A: Have you thought of a set amount of login's then a timed block? If login fails 3x/5x/10x if you want, then lock the account completely for a specified period of time.
By doing this you make it so painstaking for a brute-forcer to use, that they probably just won't bother trying. Logging every failed attempt, and more so even the thought of plain text passwords is a bad idea. Rather use the following analogy:
"If I make my house so difficult to get into, they'll try the neighbours first."
Make life difficult for the brute forcers and they won't bother.
Another option is after a set amount of failed logins, add a captcha. This again, if the captcha is good, hinders their progress dramatically.
HTH,
Kyle

A: As others have said, Logging passwords is a bad idea.
A much better idea is to throttle login attempts.
If done properly, throttling can greatly decrease the risk of password attacks as well as limiting denial of service attacks.

A: You could store hashes of failed passwords, if you really want to retain any information about them. It wouldn't allow you tomanually analyze patterns but would allow comparing failed attempts with each other.
That said, I do not think analyzing passwords would yield any useful information.

A: As others have pointed out, it's a very bad idea to store plaintext passwords and throttling/limiting login attempts is the right way to go.
If you are concerned about the security of passwords, then you should implement password policies when passwords are created, not at the time of authentication. You can then check in memory for dictionary words and have typical policies such as minimum length, must contain a number, a capital letter, etc.
Of course, password policies can be annoying to users, but they can, theoretically, ameliorate your concerns about weak passwords.
The ugly truth is that passwords are a poor way to prove identity, but the alternatives are more expensive and cumbersome.


text:
Q: Detecting User Agent to redirect on specific Jsp in struts 2 As title suggests I want to redirect the requests of mobile phones to specific page.
another way I expect is only a variable that contains information about UserAgent so That U can use that Variable in JSP to test and show specific data only
I am newbie for struts so just a    **  EXPECTING SIMPLE PROGRAM ...  **

A: Try this.
My index.jsp
<%--
    Document   : index
    Created on : Apr 17, 2013, 7:11:53 PM
    Author     : Prabhakar
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Detect</title>
        <%
        String ua = request.getHeader( "User-Agent" );
        boolean isFirefox = ( ua != null && ua.indexOf( "Firefox/" ) != -1 );
        boolean isMSIE = ( ua != null && ua.indexOf( "MSIE" ) != -1 );
        response.setHeader( "Vary", "User-Agent" );
        %>
    </head>

        <% if( isMSIE ){
      response.sendRedirect("ie.action");

     } else if(isFirefox) {
        response.sendRedirect("mozilla.action");
         }else{
        response.sendRedirect("default.action");
        } %>

    </body>
</html>


text:
Q: Cambiar formato de fechas en javascript quisiera cambiarle el formato a la fecha que actualmente estoy capturando en un formato parecido a este:
"2019/07/06 09:09:58 AM".
Aqui les dejo un ejemplo de como estoy cambiando el formato a la fecha, pero ese formato no me serve.
¿alguien me ayudaria por favor?

var fecha1 = new Date(2019, 07, 28);
var options = { year: 'numeric', month: 'numeric', day: 'numeric' };

//sin formato
var fecha2 = new Date(2019, 07, 28);
//con formato
var fecha1 = fecha1.toLocaleDateString("es-ES", options) ;

$('#Fecha1').html(fecha1);
$('#Fecha2').html(fecha2);

Fecha Con Formato

Fecha Sin Formato

A: Primero debes indicar la fecha y hora que necesitas y a continuación formatearla en el javascript de la siguiente manera:
let formatted_fecha1 = fecha1.getFullYear() + "-" + (fecha1.getMonth() + 1) + "-" + fecha1.getDate() + " " + fecha1.getHours() + ":" + fecha1.getMinutes() + ":" + fecha1.getSeconds()
Adjunto enlace donde explica muy bien distintos formatos de fecha en javascript
https://codehandbook.org/javascript-date-format/
Espero que sea de ayuda para lo que necesita

A: Como dijo Angabo, MomentJS es una buena manera para manipular las fechas. Aquí está como usarlo:

Aquí está la documentación si necesitas convertir una fecha que ya existe de otro formato. Si posible, evita native JavaScript Date Objects (los objetos nativos de fechas de JavaScript, es decir new Date()), porque es muy difícil formatearlas. Básicamente, hay que usar getFullYear(), getFullMonth(), etc. para crear una cadena para usar como parámetro para MomentJS.


text:
Q: Memory Leak in Android Phone I have seen some memory leak in my phone.
Steps :

*

*Open Browser (Home Page : www.google.com). It will fetch the Page.

*Select Back Key to come out from browser (close).

*Repeat the same steps (1-2) for 5 times.

Observer following data by "adb shell dumpsys meminfo PID (of browser) :
First Time (when open browser first time - After Step 1):
Applications Memory Usage (kB):
Uptime: 428816 Realtime: 434932
** MEMINFO in pid 899 [com.android.browser] **

                  native   dalvik    other    total
          size:    24296     6727      N/A    31023
     allocated:    24241     3955      N/A    28196
          free:       54     2772      N/A     2826
         (Pss):     3455     2259    30025    35739

(shared dirty):     2064     1772     7444    11280

  (priv dirty):     3388      548    21116    25052

 Objects

           Views:        0        ViewRoots:        0
     AppContexts:        0       Activities:        0
          Assets:        3    AssetManagers:        3
   Local Binders:       34    Proxy Binders:       28
Death Recipients:        1
 OpenSSL Sockets:        0

Second Time (After Step - 4) Opening - Closing of Browser 5 times :
Applications Memory Usage (kB):
Uptime: 473642 Realtime: 479758
** MEMINFO in pid 899 [com.android.browser] **

                  native   dalvik    other    total
          size:    45616     7559      N/A    53175
     allocated:    45322     4850      N/A    50172
          free:       29     2709      N/A     2738
         (Pss):     4602     2301    51988    58891

(shared dirty):     2060     1736     7440    11236

  (priv dirty):     4536      584    42360    47480

Objects

            Views:        0        ViewRoots:        0
      AppContexts:        0       Activities:        0
           Assets:        3    AssetManagers:        3
    Local Binders:      113    Proxy Binders:       47
 Death Recipients:        1
  OpenSSL Sockets:        0

Could you please help us to find out what data here shows which information (like what is Size, Allocated, free, Local Binders etc) and where in above data it is showing that there is memory leak.
New to all these analysis so asking basic questions :-(
Please help me for this.
Thanks
Rke

A: You know, I don't really see a memory leak here. The most common way to get memory leak is to have references to Activity which had to be destroyed. Anyway, there is a way to search for leak, there is a good article in Android developers blog about memory analysis in Eclipse with MAT and there is also a video from Google IO-2011. Try it, and maybe you'll find what's wrong.


text:
Q: Do we know when a particle has a tangled pair? By looking at a particle alone, can we tell if it has a tangled pair somewhere in the universe?
Moreover when measuring the spin of a electron, we can't predict it, unless we know the spin value of its entangled pair. So how can we be certain its random and not the case where its value is located in its entangled pair but we just don't know who it is.

A:
So how can we be certain its random and not the case where its value is located in its entangled pair but we just don't know who it is.

Does it matter? Since we can only know about the (spin) state for certain after a spin measurement, prior to that it's state is a general linear combination of up and down. In order to do any meaningful experiments we need to be able to prepare the system in any state of our choosing. Because only then do we know the dynamics of the system.
Now take the case of $2N$entangled spins each put inside a box ($2N$ boxes in total), $N$ of which are in your lab and the other $N$ in a lab 1 light years away from you. Say the spin measurements were made in that lab 2 years ago. Those spin outcomes are random, half of them up and half of them down on average. Now if they know that they are entangled with your electrons, they know the outcome of your spin measurements. If they radio that information to you, you'll know the outcome of your spin measurements. This is equivalent to having measured the spin since now you know the state. However if they don't radio the information, the outcomes are unpredictable for you, thus random.
In conclusion, the state of the system is dependent on how much you can possible know about the system (predictable probabilities of possible outcomes of measurements). If you assume a state and calculate probabilities which doesn't match with the observed outcome, it means that we are using incomplete information which means our state is wrong. This is why we prepare the system in a state because then we know as much as we can know about the system and then carry out our experiments.

A:
By looking at a particle alone, can we tell if it has a tangled pair somewhere in the universe?

Short: No
Long: Let $\rho$ be the mixed state describing your particle in Hilbertspace $A$. Then there exits a purification $\psi$ in the Hilbertspace $A\otimes B$. Purification means that $\text{tr}_B \psi = \rho$.
Therefore $\psi$ and $\rho$ cannot be distinguished by just looking at Hilberspace A. Side remark $\psi$ is not unique, but there exits an infinite amount of purification's.


text:
Q: How do I wait on async method in UWP for FileOpenPicker? I wanted to create some simple practice code in UWP that opens up a text file, then immediately appends that code with trivial text.
public MainPage()
{
    this.InitializeComponent();

    OpenFile();
    SaveFile();
}

public async void OpenFile()
{
    FileOpenPicker picker = new FileOpenPicker();
    picker.SuggestedStartLocation = PickerLocationId.Desktop;
    picker.FileTypeFilter.Add(".txt");

    DataFile = await picker.PickSingleFileAsync();
    if (DataFile == null) { return; }
}

public async void SaveFile()
{
    await FileIO.AppendTextAsync(DataFile, "" + DateTime.Now + "\n");
}

private StorageFile DataFile { get; set; }

As expected, this code returns an error since in SaveFile() method, since SaveFile() runs immediately after OpenFile() and since OpenFile() has not completed its operation of retrieving the target file for SaveFile() to use. The thing is, when I try to modify the following code in OpenFile, I receive an AggregateException error:
DataFile = picker.PickSingleFileAsync();
Task task = Task.Run( async() => DataFile = await picker.PickSingleFileAsync() );
task.Wait();

I was wondering how I can block OpenFile() until it is done retrieving the target file, before SaveFile() runs.

A: The constructor of a class should be fast and definitely shouldn't have any async methods. In your case you have been firing those methods as fire-forget, there is a race condition, where you haven't picked a file and you try to save to it. Nothing good comes from that.
Instead if you want a user to do soemthing once your MainPage is created, you may for example use Loaded event for this:
public MainPage()
{
    this.InitializeComponent();
    this.Loaded += LoadedHandler;
}

private async void LoadedHandler(object sender, RoutedEventArgs e)
{
    // assume that we want to do this only once
    this.Loaded -= LoadedHandler;
    await OpenFile();
    await SaveFile();
}

public async Task OpenFile()
{
    FileOpenPicker picker = new FileOpenPicker();
    picker.SuggestedStartLocation = PickerLocationId.Desktop;
    picker.FileTypeFilter.Add(".txt");

    DataFile = await picker.PickSingleFileAsync();
    if (DataFile == null) { return; }
}

public async Task SaveFile()
{
    await FileIO.AppendTextAsync(DataFile, "" + DateTime.Now + "\n");
}

private StorageFile DataFile { get; set; }

Note also that I've changed your methods to Tasks - you should avoid async void.


text:
Q: How can I program a message in C# after I have found an entry in another table with a DELETE query? I check in various tables whether the value to be deleted exists. Everything is working correctly, but I would like to program a message that informs the user that the entry cannot be deleted because it is still present in another table. I would like to ask you for your support. This is my query:
con.Open();
using (cmd = new SqlCommand("delete from Clinic where C_ID=@C_ID AND NOT EXISTS (SELECT * FROM Document_Type AS o WHERE o.C_ID=@C_ID)", con))
{
    cmd.Parameters.AddWithValue("@C_ID", klinikUD.Value);
    cmd.ExecuteNonQuery();
    con.Close();

}


text:
Q: imagejpeg(); not generating image on host server , working fine on localhost I have this code which is supposed to generate a captcha image of random number , it's working fine on localhost but not on my hosting, Can anyone help please? Can someone tell me where am i going wrong ?
         <?php
 session_start();
header('Content-type: image/jpeg');

 $text= $_SESSION['secure'];

 $font_size =30;
 $image_width= 110;
 $image_height=40;

 $image=imagecreate($image_width,$image_height);
 imagecolorallocate($image, 255, 255, 255);
 $text_color = imagecolorallocate($image, 0, 0, 0);

 for($x=1; $x<=30; $x++){
$x1 = rand(1,100);
$x2 = rand(1,100);
$y1 = rand(1,100);
$y2 = rand(1,100);
 imageline($image, $x1, $x2, $y1, $y2, $text_color);
}

imagettftext($image, $font_size, 0, 15, 30, $text_color, 'font.ttf', $text);
imagejpeg($image);
?>

And then i include the file that contains the above code in a new html file where i have my form and calling the image like this :
 <img src="generate.php"/>

A: Tested your script with string hello and it works

Am very sure the issue is that PHP can not located the font .. try using full system path
Try
$font = dirname ( __FILE__ ) . "/verdana.ttf" ;
if(!is_file($font))
{
    die("Missing Font");
}

A: Make sure you have NO leading spaces or newlines in your script.  Any text outputted before attempting to display an image will cause it to fail.


text:
Q: How to move/copy specific phrase/pattern to another place in txt file, and add prefix/label multiple times? I have an ics file with a lot of events. Want to improve it a bit by adding a LOCATION: tag based on the description part. Any ideas on how to do this? Do I need to do a grep/sed/awk combination or write a python script to edit it? Add a new line with a tag first or do it simultaneously with a moving pattern? Do I need to split the file into parts or just work on one? I thought about every n-line rule, but adding a blank line breaks that rule. The bad example below:
BEGIN:VEVENT
DESCRIPTION:Student plan\n\n Date: 2023.03.10 friday\n\n Time from: 17:30\n\n Time to: 19:00\n\n Hours: 2h00m\n\n Subject: Maths \n\n Room: 124A \n\n Teacher: John Smith \n\n
DTEND:20230310T190000
DTSTAMP:20230227T140621Z
DTSTART:20230310T173000
SEQUENCE:0
SUMMARY:Math
UID:dcea6c77-3c51-4101-a62a-e4949e937fa9
END:VEVENT

As you can see there is a Room: XXX \n\n pattern. It could be moved or copied - doesn't matter.
Exepted:
BEGIN:VEVENT
DESCRIPTION:Student plan\n\n Date: 2023.03.10 friday\n\n Time from: 17:30\n\n Time to: 19:00\n\n Hours: 2h00m\n\n Subject: Maths \n\n Room: 124A \n\n Teacher: John Smith \n\n
LOCATION:Room: 124A
DTEND:20230310T190000
DTSTAMP:20230227T140621Z
DTSTART:20230310T173000
SEQUENCE:0
SUMMARY:Math
UID:dcea6c77-3c51-4101-a62a-e4949e937fa9
END:VEVENT

A: Her you go:
#!/bin/sh

BASE=`basename "$0" ".sh" `

input="${BASE}.sampleIN"
cat >"${input}" <<"EnDoFiNpUt"
BEGIN:VEVENT
DESCRIPTION:Student plan\n\n Date: 2023.03.10 friday\n\n Time from: 17:30\n\n Time to: 19:00\n\n Hours: 2h00m\n\n Subject: Maths \n\n Room: 124A \n\n Teacher: John Smith \n\n
DTEND:20230310T190000
DTSTAMP:20230227T140621Z
DTSTART:20230310T173000
SEQUENCE:0
SUMMARY:Math
UID:dcea6c77-3c51-4101-a62a-e4949e937fa9
END:VEVENT
EnDoFiNpUt

awk -v matchStr="Room:" 'BEGIN{
    pshift=length(matchStr) ;
}{
    if( $0 ~ /^DESCRIPTION/ ){
        pos=index( $0, matchStr ) ;
        rem=substr( $0, pos+pshift ) ;
        split( rem, vals ) ;
        print $0 ;
        printf("LOCATION:%s %s\n", matchStr, vals[1] ) ;
    }else{
        print $0 ;
    } ;
}' "${input}"

A: Alternative solution using awk:
If line starts with 'DES', then use awk match function to capture text matching Room:  and at least one alphanumeric character [[:alnum:]]+.  Now use that capture group to redefine the current line to include a newline and the targeted text.  Now rely on the awk shorthand for default no condition {print} which is '1'.  1 is the condition, which always evaluates to true. The action is omitted, so the default {print} is performed.
awk '/^DES/ {match($0,/(Room: [[:alnum:]]+)/); $0=$0"\nLOCATION:"substr($0, RSTART, RLENGTH)}1' src.ics

Output:
BEGIN:VEVENT
DESCRIPTION:Student plan\n\n Date: 2023.03.10 friday\n\n Time from: 17:30\n\n Time to: 19:00\n\n Hours: 2h00m\n\n Subject: Maths \n\n Room: 124A \n\n Teacher: John Smith \n\n
LOCATION:Room: 124A
DTEND:20230310T190000
DTSTAMP:20230227T140621Z
DTSTART:20230310T173000
SEQUENCE:0
SUMMARY:Math
UID:dcea6c77-3c51-4101-a62a-e4949e937fa9
END:VEVENT

src.ics contents:
BEGIN:VEVENT
DESCRIPTION:Student plan\n\n Date: 2023.03.10 friday\n\n Time from: 17:30\n\n Time to: 19:00\n\n Hours: 2h00m\n\n Subject: Maths \n\n Room: 124A \n\n Teacher: John Smith \n\n
DTEND:20230310T190000
DTSTAMP:20230227T140621Z
DTSTART:20230310T173000
SEQUENCE:0
SUMMARY:Math
UID:dcea6c77-3c51-4101-a62a-e4949e937fa9
END:VEVENT


text:
Q: Jwt with new client I have implemented JWT auth
I have function in startup file like
public void ConfigureOAuth(IAppBuilder app)
        {
            var issuer = "http://jwtauthzsrv.azurewebsites.net";
            //var audience = "fd9eeeb25b694ff1bfd2260cf0d665c3";
            //var secret = TextEncodings.Base64Url.Decode("ixioSD5UPMMfGFUvxfblU3elZAnUvtoleVI0qu_7SrI");
            List<string> secret = new List<string>();
            List<string> audience = new List<string>();

            secret.Add(Convert.ToBase64String(TextEncodings.Base64Url.Decode("adFu3IhHjNibtVzy7Uon7l9CQE97XQ8YOKnLzLWlb1s")));
            //secret.Add(Convert.ToBase64String(TextEncodings.Base64Url.Decode("YqnwwJFI6HTQheAGvHI9ycuhgRmkpJDgOQDkDnahG2I")));
            // secretkeys.Add(TextEncodings.Base64Url.Decode("YqnwwJFI6HTQheAGvHI9ycuhgRmkpJDgOQDkDnahG2I").ToString());
            audience.Add("746b0e9e0bb44bfda086bc7f03f427c5");
           // audience.Add("7ef27cd3397d41e4848c3a85cca9e737");

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences =  audience.AsEnumerable(),//new[] { audience },
                    //AllowedAudiences = new[] { audience },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                        //new SymmetricKeyIssuerSecurityTokenProvider(issuer,secret.AsEnumerable())
                    },
                    Provider = new OAuthBearerAuthenticationProvider
                    {
                        OnValidateIdentity = context =>
                        {
                            context.Ticket.Identity.AddClaim(new System.Security.Claims.Claim("newCustomClaim", "newValue"));
                            return Task.FromResult<object>(null);
                        }
                    }
                });

        }

I assume whenever an api with authorize attribue is being called it should call ConfigureOAuth so that it should load all cient id from database and validate through jwt, but while debugging I saw startup file runs only when I run the application,
How can I make this to call ConfigureOAuth this function whenever any api getting called, so that it should load new clientid as well and validate.
UPDATE
app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences =  select from database),

the above line is being initialized only once when I publish and deploy project, but not when a new api call is being made.
Problem occurring if a new user has been created, the id of new user is not coming in allowed audiences
Thanks

A: ConfigureOAuth should only run once at startup, so the behavior is correct.
With app.UseJwtBearerAuthentication you add a middleware for authentication to the request pipeline. You already add the allowed audiences to the configuration, so it won't be loaded again during processing of an [Authorize] decorated api. The middleware will then check for the presence of an authorization header in the request and check if the provided JWT is valid and the audience matches the configured audiences.
Update in reaction to your update:

Problem occurring if a new user has been created, the id of new user is not coming in allowed audiences

"Audiences" are not the users, but the resource servers for which the token can be used, see also here: JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?
And the user authentication doesn't happen when you process a request which is decorated with [Authorize] but already much earlier when the user requests a token at the token endpoint. The JWT auth middleware will only check if the token that it finds in the Authorization header of the request has an aud value that matches the AllowedAudiences. But at this point, the user is already authenticated.
The place where you access your user database would be in a different class, e.g
public class MyAuthProvider : OAuthAuthorizationServerProvider
{
    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
    if(Authenticate(context.UserName, context.Password))
        ...
    }
}

That's where you authenticate the user, add claims to the JWT and finally create the JWT token.
I recommend reading Taiseer Joudehs blog: http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/


text:
Q: separate random numbers in tkinter This code showed me some random numbers on the right side on my screen.
from Tkinter import *
import math
from random import randrange

number=Tk()
number.geometry("1308x720")
number.config(bg="black")
ECG=randrange(0,1000);SP=randrange(0,1000);PLES=randrange(0,1000);show=randrange(0,1000)
c1=StringVar();c2=StringVar();c3=StringVar();c4=StringVar()
c1.set(ECG);c2.set(SP);c3.set(PLES);c4.set(show)
valor_c1=Label(number,textvariable=c1,width=int(c1.get())//10,height=1,fg="red",anchor="ne",bg="black").grid(row=0,column=2, sticky=E)
valor_c2=Label(number,textvariable=c2,width=int(c2.get())//10,height=1,fg="red",anchor="ne",bg="black").grid(row=0,column=2, sticky=E)
valor_c3=Label(number,textvariable=c3,width=int(c3.get())//10,height=1,fg="red",anchor="ne",bg="black").grid(row=0,column=2, sticky=E)
valor_c4=Label(number,textvariable=c4,width=int(c4.get())//10,height=1,fg="red",anchor="ne",bg="black").grid(row=0,column=2, sticky=E)
number.grid_columnconfigure(2, weight=1)
number.mainloop()

Now I need to separate the second number 4,5 cm away from the edge, the third number 9 cm away from the edge and the fourth number 13,5 cm away from the edge.
I tried to separate one number of the other changing the number of row, but did not work
To summarizing, my question is: ¿How to separate one number of the other?

A: Use pady or ipady option. See Tkinter.Grid.grid.
Label(number,textvariable=c1,width=int(c1.get())//10,height=1,fg="red",anchor="ne",bg="green").grid(row=0,column=2, sticky=E, pady=10)
Label(number,textvariable=c2,width=int(c2.get())//10,height=1,fg="blue",anchor="ne",bg="snow").grid(row=4,column=2, sticky=E, pady=10)
Label(number,textvariable=c3,width=int(c3.get())//10,height=1,fg="cyan",anchor="ne",bg="grey").grid(row=8,column=2, sticky=E, pady=10)
Label(number,textvariable=c4,width=int(c4.get())//10,height=1,fg="gold",anchor="ne",bg="blue").grid(row=16,column=2, sticky=E, pady=10)
#                                                                                ^^^^^^^

BTW, you can specify the padding as pixel, not as cm.


text:
Q: AUTOHOTKEY - How can I get a hotstring to initiate without a preceding space? I've got a hotkey definition:
:*:()::(){left}

If I write something like this:
word ()

The cursor ends up between the parentheses.  :)  But if I write something like this:
function()

The cursor ends up to the right of the parentheses.  How can I change my hotstring to always put my cursor between the parentheses, regardless of a preceding space?

A: :?*:()::(){left}

? (question mark): The hotstring will be triggered even when it is inside another word. Use ?0 to turn this option back off.
https://autohotkey.com/docs/Hotstrings.htm#Options


text:
Q: Gridlines that overlap with axes spines have different width from other gridlines I'm using Seaborn to make some plots using the whitegrid style. After calling despine(), I'm seeing that the gridlines that would overlap with the axes spines have smaller linewidth than the other gridlines. But it seems like this only happens when I save the plots as pdf. I'm sharing
three different figures with different despine configurations that show the effect.
Does anyone know why this occurs? And is there a simple fix?
PDF plot with all spines
PDF plot that despines all axes
PDF plot that despines left, top, and right axes
Code:
splot = sns.boxplot(data=df, palette=color, whis=np.inf, width=0.5, linewidth = 0.5)
splot.set_ylabel('Normalized WS')
plt.xticks(rotation=90)
plt.tight_layout()
sns.despine(left=True, bottom=True)
plt.savefig('test.pdf', bbox_inches='tight')

A: Essentially what's happening here is that the grid lines are centered on the tick position, so the outer half of the extreme grid lines are not drawn because they extend past the limits of the axes.
One approach is to disable clipping for the grid lines:
import numpy as np
import seaborn as sns

sns.set(style="whitegrid", rc={"grid.linewidth": 5})
x = np.random.randn(100, 6)

ax = sns.boxplot(data=x)
ax.yaxis.grid(True, clip_on=False)
sns.despine(left=True)

A: My hacking solution now is to not despine the top and bottom axes and make them the same width as the gridlines. This is not ideal. If someone can point out a way to fix the root cause, I will really appreciate that.


text:
Q: Android unable to retrieve nearby places using google api I am trying to get the nearby places of the location I send by using the google map's api. Below is the url(https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&keyword=cruise&key=YOUR_API_KEY).I created a POJO class using DTO Generator plugin.But in the response method of the retrofit the status variable in the POJO class gives me 'REQUEST_DENIED'.(Main Activity.java)
Log.e("Res",response.body().getStatus());
Am I using retrofit the right way?
RetrofitClient.java:
public class RetrofitClient {
    public static Retrofit retrofit=null;
     static final String baseurl="https://maps.googleapis.com/maps/api/place/nearbysearch/";
    public static Retrofit getClient()
    {
        if (retrofit==null)
        {
            retrofit=new Retrofit.Builder().baseUrl(baseurl).addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
    }
}

NearbyApi.java:
public interface NearbyApi {
    @GET("json?")
    Call<NearbyPlaces> getDetails(@Query("location") String loc,
                                  @Query("radius") String radius,
                                  @Query("type") String type,
                                  @Query("keyword") String keyword,@Query("key") String key);

}

MainActivity.java:
String loc="-33.8670522,151.1957362";
    String radius="1500";
    String type="restaurant";
    String keyword="cruise";
    String key="****";
    NearbyApi nearbyApi=RetrofitClient.getClient().create(NearbyApi.class);
                        Call<NearbyPlaces> call=nearbyApi.getDetails(loc,radius,type,keyword,key);
                        call.enqueue(new Callback<NearbyPlaces>() {
                            @Override
                            public void onResponse(Call<NearbyPlaces> call, Response<NearbyPlaces> response) {

    //                                Log.e("Res",response.body().getStatus());
                                Log.e("Res",response.body().getStatus());
                                }

                            @Override
                            public void onFailure(Call<NearbyPlaces> call, Throwable t) {
                                Log.e("Response","Failure");
                            }
                        });

(NearbyPlaces.java)POJO class:
public class NearbyPlaces {

    @Expose
    @SerializedName("status")
    private String status;
    @Expose
    @SerializedName("results")
    private List<Results> results;
    @Expose
    @SerializedName("html_attributions")
    private List<String> html_attributions;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public List<Results> getResults() {
        return results;
    }

    public void setResults(List<Results> results) {
        this.results = results;
    }

    public List<String> getHtml_attributions() {
        return html_attributions;
    }

    public void setHtml_attributions(List<String> html_attributions) {
        this.html_attributions = html_attributions;
    }

    public static class Results {
        @Expose
        @SerializedName("vicinity")
        private String vicinity;
        @Expose
        @SerializedName("types")
        private List<String> types;
        @Expose
        @SerializedName("scope")
        private String scope;
        @Expose
        @SerializedName("reference")
        private String reference;
        @Expose
        @SerializedName("rating")
        private int rating;
        @Expose
        @SerializedName("plus_code")
        private Plus_code plus_code;
        @Expose
        @SerializedName("place_id")
        private String place_id;
        @Expose
        @SerializedName("photos")
        private List<Photos> photos;
        @Expose
        @SerializedName("opening_hours")
        private Opening_hours opening_hours;
        @Expose
        @SerializedName("name")
        private String name;
        @Expose
        @SerializedName("id")
        private String id;
        @Expose
        @SerializedName("icon")
        private String icon;
        @Expose
        @SerializedName("geometry")
        private Geometry geometry;

        public String getVicinity() {
            return vicinity;
        }

        public void setVicinity(String vicinity) {
            this.vicinity = vicinity;
        }

        public List<String> getTypes() {
            return types;
        }

        public void setTypes(List<String> types) {
            this.types = types;
        }

        public String getScope() {
            return scope;
        }

        public void setScope(String scope) {
            this.scope = scope;
        }

        public String getReference() {
            return reference;
        }

        public void setReference(String reference) {
            this.reference = reference;
        }

        public int getRating() {
            return rating;
        }

        public void setRating(int rating) {
            this.rating = rating;
        }

        public Plus_code getPlus_code() {
            return plus_code;
        }

        public void setPlus_code(Plus_code plus_code) {
            this.plus_code = plus_code;
        }

        public String getPlace_id() {
            return place_id;
        }

        public void setPlace_id(String place_id) {
            this.place_id = place_id;
        }

        public List<Photos> getPhotos() {
            return photos;
        }

        public void setPhotos(List<Photos> photos) {
            this.photos = photos;
        }

        public Opening_hours getOpening_hours() {
            return opening_hours;
        }

        public void setOpening_hours(Opening_hours opening_hours) {
            this.opening_hours = opening_hours;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getIcon() {
            return icon;
        }

        public void setIcon(String icon) {
            this.icon = icon;
        }

        public Geometry getGeometry() {
            return geometry;
        }

        public void setGeometry(Geometry geometry) {
            this.geometry = geometry;
        }
    }

    public static class Plus_code {
        @Expose
        @SerializedName("global_code")
        private String global_code;
        @Expose
        @SerializedName("compound_code")
        private String compound_code;

        public String getGlobal_code() {
            return global_code;
        }

        public void setGlobal_code(String global_code) {
            this.global_code = global_code;
        }

        public String getCompound_code() {
            return compound_code;
        }

        public void setCompound_code(String compound_code) {
            this.compound_code = compound_code;
        }
    }

    public static class Photos {
        @Expose
        @SerializedName("width")
        private int width;
        @Expose
        @SerializedName("photo_reference")
        private String photo_reference;
        @Expose
        @SerializedName("html_attributions")
        private List<String> html_attributions;
        @Expose
        @SerializedName("height")
        private int height;

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        public String getPhoto_reference() {
            return photo_reference;
        }

        public void setPhoto_reference(String photo_reference) {
            this.photo_reference = photo_reference;
        }

        public List<String> getHtml_attributions() {
            return html_attributions;
        }

        public void setHtml_attributions(List<String> html_attributions) {
            this.html_attributions = html_attributions;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }
    }

    public static class Opening_hours {
        @Expose
        @SerializedName("open_now")
        private boolean open_now;

        public boolean getOpen_now() {
            return open_now;
        }

        public void setOpen_now(boolean open_now) {
            this.open_now = open_now;
        }
    }

    public static class Geometry {
        @Expose
        @SerializedName("viewport")
        private Viewport viewport;
        @Expose
        @SerializedName("location")
        private Location location;

        public Viewport getViewport() {
            return viewport;
        }

        public void setViewport(Viewport viewport) {
            this.viewport = viewport;
        }

        public Location getLocation() {
            return location;
        }

        public void setLocation(Location location) {
            this.location = location;
        }
    }

    public static class Viewport {
        @Expose
        @SerializedName("southwest")
        private Southwest southwest;
        @Expose
        @SerializedName("northeast")
        private Northeast northeast;

        public Southwest getSouthwest() {
            return southwest;
        }

        public void setSouthwest(Southwest southwest) {
            this.southwest = southwest;
        }

        public Northeast getNortheast() {
            return northeast;
        }

        public void setNortheast(Northeast northeast) {
            this.northeast = northeast;
        }
    }

    public static class Southwest {
        @Expose
        @SerializedName("lng")
        private double lng;
        @Expose
        @SerializedName("lat")
        private double lat;

        public double getLng() {
            return lng;
        }

        public void setLng(double lng) {
            this.lng = lng;
        }

        public double getLat() {
            return lat;
        }

        public void setLat(double lat) {
            this.lat = lat;
        }
    }

    public static class Northeast {
        @Expose
        @SerializedName("lng")
        private double lng;
        @Expose
        @SerializedName("lat")
        private double lat;

        public double getLng() {
            return lng;
        }

        public void setLng(double lng) {
            this.lng = lng;
        }

        public double getLat() {
            return lat;
        }

        public void setLat(double lat) {
            this.lat = lat;
        }
    }

    public static class Location {
        @Expose
        @SerializedName("lng")
        private double lng;
        @Expose
        @SerializedName("lat")
        private double lat;

        public double getLng() {
            return lng;
        }

        public void setLng(double lng) {
            this.lng = lng;
        }

        public double getLat() {
            return lat;
        }

        public void setLat(double lat) {
            this.lat = lat;
        }
    }
}

A: Provided that you actually have an API Key already, if not,
https://developers.google.com/places/web-service/get-api-key
Once you get your api key and you want to enable api and services, you can always go to your api console and enable apis and services,
Go to https://console.cloud.google.com/apis/dashboard?YOUR_PROJECT
Click in the Enable Apis Button

Enable the APIs and services that you want to use.
You should enable Maps SDK for Android and any other services you might want to use.
UPDATE:
If you are making an Http request (e.g. @GET), please make sure that you don't place a restriction on your API in the api console.  So you need to go to your generated key and find the following and set to no restrictions,

What will happen if you select Android only?
You'll be able to use any objects and methods in the selected SDK (e.g. places/maps).
For example, PlacePicker object in places API.
I am giving reference to places sdk from developers website,
https://developers.google.com/places/android-sdk/intro
But if you want make HTTP request then it will get denied as you have restrictions placed in your key.


text:
Q: Where and how do I store an access token? I am using the IGDB API. It has recently changed to require OAuth tokens for authorization.
This is the structure of the returned token:
{
   "access_token": "prau3ol6mg5glgek8m89ec2s9q5i3i",
   "expires_in": 5587808,
   "token_type": "bearer"
}

My current method is to store the token in Firestore as a document and run a scheduled script everyday to see if the token is 24 hours or less from expiring. If so, the script would replace the token in the database.
The API calls currently happen directly in the app, without a proxy, and would use the token stored in Firestore.
Am I over complicating this? Are there issues with this method?

A: It's impossible to say exactly what's right or wrong without knowing the full architecture of your application. But, if you check with OAuth 2.0 Threat Model and Security Considerations - Store Secrets in Secure Storage, it says following,

Moreover, most modern smartphone operating
systems even support the storage of application-specific data in
separate areas of file systems and protect the data from access by
other applications.

and

Note: Applications
should ensure that confidential data is kept confidential even after
reading from secure storage, which typically means keeping this data
in the local memory of the application.

So, make sure the access token is stored in a location which cannot be exploited by a different application running on the same system. Furthermore, make sure no malicious party can simply access this location and get hold of the access token. These are the recommendations you can follow.


text:
Q: Bootstrap Multi-level dropdown pin the sub menu's on DOM In Brief, I'm trying to use Bootstrap's Multilevel Dropdown feature.
Here we'r facing a issue like if you take mouse cursor out of drop-down menu or drop-down submenu then its getting hide by default. But i wanted to pin it even after mouse cursor goes out of drop-down menu or drop-down submenu. & it should get hide once i do click on DOM or any where on the page.
Here I'm attaching some reference of multi-level menu.
Bootply

If any one of us had something for this please share with me.
I found something similar to my requirement. But Its developed in Bootstrap v3. I need this in Bootstrap v2.3.2. Here is the twitter-bootstrap-multilevel-dropdown-menu

A: My answer for multilevel dropdown menu for bootstrap v3 also works for v2.3.2. Here is the answer: https://stackoverflow.com/a/18025399/2214222
Also,
Bootply example for v2.3.2

A: So I hope I don't forget something in the answer :
Bootply : http://bootply.com/113016
JS :
$('.dropdown-submenu').on('mouseover', function(){
    $(this).find('.dropdown-menu').first().show();
});

$(document).on('click', function(){
    $('.dropdown-menu .dropdown-menu').hide();
});

CSS [see commented lines] :
.dropdown-submenu{position:relative;}
.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px;}
//.dropdown-submenu:hover>.dropdown-menu{display:block;}
.dropdown-submenu>a:after{display:block;content:" ";float:right;width:0;height:0;border-color:transparent;border-style:solid;border-width:5px 0 5px 5px;border-left-color:#cccccc;margin-top:5px;margin-right:-10px;}
//.dropdown-submenu:hover>a:after{border-left-color:#ffffff;}
.dropdown-submenu.pull-left{float:none;}.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px;}


text:
Q: Onclck listener with fragments
*

*Hello, So I followed the Android Developer website to create some
simple tabs in Android with fragments. The tabs fully work and
display the content they are supposed to. However, I am now trying
to intergrate it with this AndroidHive Login tutorial. I have
set up the XML properly and the MainActivity from the Login tutorail
now shows on my first tab. I am now trying to setup the onclick
listener for the logout button but it seems my intent params are not
working and also the finish method doesn't work:
private void logoutUser() {
 session.setLogin(false);
 db.deleteUsers();
 Intent intent = new Intent(OneFragment.this, LoginActivity.class);
 startActivity(intent);
 finish();
}

I'm guessing it has to do with the fact that my clsss isnt an
activity?
public class TabOne extends Fragment implements  View.OnClickListener {.....}

*Also I am not following his tutorial exactly and am coding some elements of the project how I prefer it (I've been studying pure Java at university for 2 yeats now). But inside his MainActivity class he has to variables as follows (the classes are available in his login tutorial)

*

*private SQLiteHandler db;

*private SessionManager session;

and he initalises them in the onCreate as follows:
    db = new SQLiteHandler(getApplicationContext());
    session = new SessionManager(getApplicationContext());

However, because I am using fragments and not activities I can't do this so after some researching I tried this:
    db = new SQLiteHandler(getActivity().getApplicationContext());

    session = new SessionManager(getActivity().getApplicationContext());

It has removed the errors on Android Studio but I am not 100% sure it will work (I still have the above error in my code so I am unable to test) - Can you please clarify if this would work also - again all his classes are in the link above including session and sqllite.
Edit 1 - Sorry I should have added this, I used cases and called the logout method:
  @Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnLogout:
            logoutUser();
    }
}

Thank you, if any further information is required please ask and I shall update this post

A: I do not know if my way of getting the Application's Context is the correct way, but I have created a public method in my MainActivity (that shows the Fragments) that returns the application context. If you go this route, you can call MainActivity.getContext() (or the name of your method) and can get that Activity's context inside of your fragment.

A: You have to access your main activity context from the fragment to able to call methods which belong to activity class. for your case use the folowing
private void logoutUser() {
  session.setLogin(false);
  db.deleteUsers();
  Intent intent = new Intent(getActivity(), LoginActivity.class);
  startActivity(intent);
  getActivity().finish();
}


text:
Q: How to get Reply data of an Mail using python Hello I am using imaplib to retrieve inbox mails using python but I am unable to get the reply of the mail. How to get it can anyone help me with this?
this is the code
import email
import imaplib

EMAIL = "user_email"
PASSWORD = "user_password"
SERVER = 'imap.gmail.com'

mail = imaplib.IMAP4_SSL(SERVER)
mail.login(EMAIL, PASSWORD)
mail.select('inbox')
status, data = mail.search(None, 'ALL')
mail_ids = []
for block in data:
        mail_ids += block.split()

status, data = mail.fetch(mail_ids[-2], '(RFC822)')


text:
Q: How to disable bluebooth mouse battery on Power Indicator I use Ubuntu 14.04v on my HP ENVY 14 (14-k030TX)
Power Indicator contains my Bluetooth mouse's battery but it's wrong , and it will an average of the battery level on my Power Indicator, so the battery level display on Power Indicator is wrong.
How can I remove it from Power Indicator, I only want see my laptop's battery level?


text:
Q: Stop Python input when a specific character is entered I'm writing a Python program (on OS X/Linux) in which a user has to type some words in a while loop. This is the relevant part of it:
i = 0
array = []
while (i < 10):
   array.append(raw_input("Prompt: "))
   i = i + 1

However I'd like to stop the input as soon as the user types a SPACE, without the need to press ENTER.
I know I can't do this using raw_input, however I did not find any way to achieve what I'm trying to do. Basically I would like the user to be able to type one word after the other, using the SPACE button instead of ENTER to input the next word.
Do you have any idea? Thanks in advance.

A: It's not possible with raw_input, input or sys.stdin.read(1) either. There is no generic solution which works on every operating system.
Here is how to read a single character from the user in Python, without pressing Enter: Python read a single character from the user
Then you need to process each character in a for loop.


text:
Q: How to modify the class "Array" in Ruby? I'm new about ruby! I just wanna do the following:
module Functional
  def filter
  end
end

class Array
  include Functional
  def filter
  end
end

a = [1, -2, 3, 7, 8]
puts a.filter{|x| x>0}.inspect      # ==>Prints out positive numbers

How could I modify the method "filter" in Array?
Could anybody help me? Thank you

A: class Array
  alias filter :select
end

a = [1, -2, 3, 7, 8]
a.filter{|x| x > 0}

A: I think what you're looking for is this:
module Functional
  def filter
    return self.select{ |i| i > 0 }
  end
end

class Array
  include Functional
end

a = [1, -2, 3, 7, 8]
puts a.filter{|x| x>0}.inspect
#=>[1, 3, 7, 8]

Although I think you can save yourself the trouble by just using select -- there's no need to reimplement it.


text:
Q: Ajax returning object instead of data What is the correct way to handle Ajax success callback events using jquery?
In my code, when I run instead of displaying data, it alerts object:object. However, if I use say msg.box it returns the data correctly.
I am trying to create an if statement where if text equals a certain word then the variable from json is placed in the html of the result div BA_addbox.
I cannot seem to get this to work and would be grateful if someone could point out my error. I have only included the relevant code as the form is posting the correct data and the php code is catching all the posts. Many thanks.
ajax code
$.ajax({
    type: "POST",
    url: "/domain/admin/requests/boxes/boxesadd.php",
    data: formdata,
    dataType: 'json',
    success: function(msg){
        if(msg == "You need to input a box") {
            $("#BA_addbox").html(msg.boxerrortext);
        }
        else {
            $("#BA_addbox").html(msg.box);
        }

        //alert(msg);
        console.log(msg);
        //$("#BA_addbox").html(msg.box);

        //$("#formImage .col_1 li").show();
        //$("#BA_boxform").get(0).reset();
        //$("#boxaddform").hide();
    }
});

boxesadd.php
$box = mysql_real_escape_string($_POST['BA_box']);
$boxerrortext = "You need to input a box";

if (isset($_POST['submit']))    {
    if (!empty($box)) {

        $form = array('dept'=>$dept, 'company'=>$company, 'address'=>$address, 'service'=>$service, 'box'=>$box, 'destroydate'=>$destroydate, 'authorised'=>$authorised, 'submit'=>$submit);

        $result = json_encode($form);

        echo $result;

    }
    else
    {

        $error = array('boxerrortext'=>$boxerrortext);

        $output = json_encode($error);

        echo $output;
        //echo "You need to input a box";

    }
}

A: In javascript associative arrays are called objects, so there's no bug in the transmitted data.
Why do you compare msg to "You need to input a box"? You cannot compare object and string, this makes no sense.
if(typeof msg.boxerrortext !== "undefined" && msg.boxerrortext == "You need to input a box") {
    $("#BA_addbox").html(msg.boxerrortext);
} else {
    $("#BA_addbox").html(msg.box);
}

A: Try this instead:
if(msg.boxerrortext) {
  $("#BA_addbox").html(msg.boxerrortext);
}
else {
  $("#BA_addbox").html(msg.box);
}

Hope this will help !!


text:
Q: Dimension de la imagen en una galeria de materialize CSS Hola amigos  tengo el siguiente problema tengo una galeria con el framework materialize CSS estoy intentando hacer que las animaciones se vean completamente pero no me las muestra completamente todas ?
alguien sabe porque ?
Mi codigo de la galeria:

Lovi Acabados

Las mejores piedras de sonora

Necesitas decorar tu casa, somos los expertos.

Virgenes de Guadalupe

Tenemos las mejores estatuas de la virgen de Guadalupe hechas a mano por nuestros expertos.

Amas a los animales !

Tenemos las mejores esculturas de animales decorativos para tu Hogar.

Nos has decorado tu casa!

Decora tu casa con las mejores piedras de sonora.

Dale un toque unico a tu casa

Lovi Acabados tenemos las mejores decoracion del estado.

Dale Paz y alegria a tu casa!

En Lovi Acabados tenemos para ti las virgenes de guadalupe talladas a mano.

Dale elegancia a tu casa!

Dale elegancia a tu casa con las mejores esculturas de piedra para tu casa.

Y Muchos Mas Productos!

Lovi Acabados es la mejor.

Necesito hacer que las imagenes se vean completas pero solo se ve un pedaso de la imagen alguien sabe como hacer que sea vea completa.

A: a lo que entendí sobre tu pregunta
1- si no logras ver todas las imágenes con el slider es por la barra de navegación, es decir esta sobre tu slider, lo que necesitas es ajustar "position" del valor "absolute" a "relative",
otro camino no tan "pro" es ajustar "margin-top" hasta que se vea la imagen completa, espero haber sido de ayuda.


text:
Q: what is noir.server/start option :ns for? What is the :ns key for the option map supplied to noir.server/start used for? I see that if you leave out :ns a randomly generated symbol is used. From looking through the Noir source I could not find anywhere where this symbol is used. Does anyone know if this is currently being used for something / if there are plans for this key?

A: Check out this file in Noir source code. This provides a middle ware to handle exceptions - wrap-exceptions and the code in this file uses :ns option to parse the exception and get stack trace data in a map object which has this :ns key.


text:
Q: IONIC/Cordova video streaming im using the latest ionic version (it's v 3.9.2),
and im trying to post a live streaming via RTMP, & i don't know how to start !?
please help me with some documentations, informations or code snippets
sorry for my english & thanks

A: Im working on this for an app. Im using Microsoft Azure's - Azure Media Services. It has Live Streaming RTMP ingest and fragmented mp4, while i've not made much headway with the fragmented mp4 ingest - I have made some headway with RTMP but have not yet started implementing code - should be another 48 hours before I'm at that point so ill edit this post shortly.
I've managed to make it work natively in Android Studio, so that simply tells me the device supports the feature via this Git project - and needed to rule out an issue at the Azure end - which worked perfectlty:
https://github.com/ant-media/LiveVideoBroadcaster
here is the relevant Cordova dependency you'll need to do the same and you will need to do the following:
Install the dependency: https://github.com/disono/cordova-rtmp-rtsp-stream
$ cordova plugin add cordova-rtsp-rtmp-stream

Mehods:
videoStreamer.streamRTSP('uri', [success], [failed]);
videoStreamer.streamRTMP('uri', [success], [failed]);
videoStreamer.streamRTMPAuth('uri', 'your-username', 'your-password', [success],[failed]);

I will update this thread with what I come up with!