text:
Q: url rewriting to redirect to correct javascript file version I recently read on Meta about some browser not flushing their cache even after reading a script url of this form
myscript.js?v=1234
so to go around the problem i am thinking about implementing a solution i also read but without any details given to it. something like myscript-1234.js and reroute to the actual correct file, but i have a doubt now.
Should i rewrite that url to myscript.js or to myscript.js?v=1234   ? I am actually confused as to how it even going to make a difference to have a rewriting.

A: Your rewriting should not redirect to any other URL (which would the be fetched by the browser), but should be "internal" on your server.
What I mean is that when receiving a request for "myscript-1234.js", your server should instead serve the content of the myscript.js file ; which will always be the last version.
In the end :

*

*For the client the is a different URL each time you update the file on the server : myscript-1234.js, myscript-1235.js, myscript-1236.js, ...

*

*This is why the browser will try to re-fetch the file from the server : as it's not the same name, it will not have the file in cache

*But, for the server, there is always one and only one file : myscript.js

*And you're using some "rewrite" rule so thr server just removes the -XYZ portion of the file name before trying to read it from disk.


text:
Q: ShopifyAPI method list I went trough the the shopifyApi documentation and it's explaining how to communicate with the API via post/put/get http verbs.
I am coding in Ruby and I was wondering where I could find a list of all the methods available (like product.add_metafield(params)).
I checked the gem server and didn't find any RDOC available for the api.
Thank you

A: Here is a neat trick. At your command-line try gem which shopify_api. That will list out the current version you are using for your current Ruby. Of course with RVM or RBEnv these vary wildly.
Copy and paste the result to your clipboard. An example from my CLI is:
/Users/fuzzy/.rvm/gems/ruby-1.9.3-p194/gems/shopify_api-3.0.1/lib/shopify_api.rb

You only need this part...
/Users/fuzzy/.rvm/gems/ruby-1.9.3-p194/gems/shopify_api-3.0.1/lib

With that in your clipboard, type subl or mate or vim or whatever your text editor is and paste in that path. You'll then have the gem at your disposal. If you navigate to the shopify_api/resources folder you'll see the product.rb file, showing off some methods you can use. You can see how most resources work this way. Learning Active Resource can also go a long way to showing off how the API gem provides functionality.
You can hack the gem once you get past this stage of exploration. You can re-open the modules and classes and add your own methods. Pretty neat stuff.
The command line interface based on Thor is also in there, and worth a good look. That is one of the coolest aspects of the gem in my opinion. see shopify_api/cli.rb

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting the relative path from current directory to a folder given as argument To be more specific:
Let's say current directory is ~/Bash/ and which contains ~/Bash/test/
myscrip.sh .

should get the output "Generating Bash.html"
myscrip.sh ../Bash/test

or
myscrip.sh test/

both should get "Generating ./test.html"
This is my attempt at getting relative path but it's my first script,
so i'm not very resourceful yet.
#! /bin/bash

[ $# -ne 1 ] \
  && echo -e " Script usage: \n\t `basename $0` <folder>" \
  && exit 1

[ -d "$1" ] || { echo "Folder doesn't exist" && exit 2; }

folder=`find -maxdepth 1 -name "${1%/}"`
echo -e "Generating $folder.html"

A: Instead of
folder=`find -maxdepth 1 -name "${1%/}"`

use
folder=$(basename "$(realpath -s "$1")")

The rest looks okay.

*

*realpath (part of the GNU coreutils) will give you the canonicalized version of the path it is given as an argument. realpath . will print the same as pwd, realpath ../Bash/test will give you /home/user/Bash/test and so forth. The -s argument prevents resolution of symlinks.

*basename isolates the innermost directory name from it, which is the one you wanted.

*$() does command substitution; it is similar to backticks but more easily nested.

One caveat: You will want to check for "$1" == "/", where this logic ultimately breaks down (folder becomes /, and without special handling, you'd attempt to write to /.html). Whether you want to forbid it or do something special for it is a design question you'll have to answer yourself.


text:
Q: How to read 2nd level sub-directory text file in vb.net I have a little program which is supposed to read text from a text file.
The text file is contained in a sub-directory as follows:
Customer > Sub-directory 1 > Sub- directory 2 > Text file
The code I am using is:
Dim ti = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Customers\" & TextBox1.Text))

Dim du As String = Path.Combine(ti.FullName, TextBox2.Text, TextBox3.Text + ".txt")

Dim ObjectReader As New System.IO.StreamReader(du)

Where:

*

*TextBox1 = Name of the Customer

*TextBox2 = Name of product

*TextBox3 = Reference

The error I am getting is:
"Could not find a part of the path 'C:\Users\Mark\Desktop\Customers\Biscuits\Reference.txt".
Please how do I rectify this? I am using Visual Basic 2010 Express. Thank you.

A: Why not try:
 Dim ti2 = (Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Customers\" & TextBox1.Text))

    Dim du = Path.Combine(ti2, TextBox1.Text, TextBox2.Text, TextBox3.Text + ".txt")


text:
Q: How do I make a top level query on belongsToMany association in Sequelize? I need to get all Tags that belongs to a Post.
First, I managed Post and Tag via belongsToMany association as like as table post_tag. These models were built as below:
Post.belongsToMany(Tag, {
  as: 'tags',
  through: {
    model: PostTag,
    unique: true,
  },
  foreignKey: 'post_id',
  constraints: true
});

Tag.belongsToMany(Post, {
  as:'posts',
  through: {
    model: PostTag,
    unique: true,
  },
  foreignKey: 'tag_id',
  constraints: true
});

Then, I wrote a good working statment like this:
Post.findAll({
  include: [{
    model: Tag, as: 'tags',
    attributes: ['id','name'],
    through: {attributes:[]}
  }]
})
//JSON result
[
  {
    "title": "Post title 1",
    "tags": [
      {"id":1, "name": "tagA"},
      {"id":2, "name": "tagB"}
    ]
  },
  {
    "title": "Post title 2",
    "tags": [
      {"id":1, "name": "tagA"},
      {"id":3, "name": "tagC"}
    ]
  }
]

When I was trying to filter post by tagA, I still got 2 post same above. But tagB and tagC were lost in the nested propery tags:
    Post.findAll({
      include: [{
        model: Tag, as: 'tags',
        attributes: ['id','name'],
        through: {attributes:[]},
        where: {name:'tagA'} // <--- Add filter here
      }]
    })
    //JSON result
    [
      {
        "title": "Post title 1",
        "tags": [
          {"id":1, "name": "tagA"}  // <-- tagB was gone
        ]
      },
      {
        "title": "Post title 2",
        "tags": [
          {"id":1, "name": "tagA"}  // <-- tagC was gone
        ]
      }
    ]

I read Sequelize document which guides us move the where to top level, but it only works with hasMany association.
   Post.findAll({
      where: {'$tags.name$':'tagA'} // <--- move query to top here follow the guide
      include: [{
        model: Tag, as: 'tags',
        attributes: ['id','name'],
        through: {attributes:[]},
      }]
    })

Is there any way to keep tagB and tagC in the result?

A: Post.findAll where "TagA" return id post and then each loop > get full infomation include tags inside !


text:
Q: MapView onCreate throws NullPointerException on LG devices First of all, this problem is for me only reproducible on LG devices (LG G4 and G5) running Android 6. The problem was introduced through the last update of the google play services. If I manually downgrade the google play services on my LG devices the error is gone. Unfortunately I cannot tell my users to do this, so I need to find another solution. As this error is reproducible with my app in the play store I can be certain the error was not introduced through my own code changes.
The error occurs through calling the onCreate() method inside MapView. I subclassed MapView and have my own class like this
public class MyMap extends MapView implements OnMapReadyCallback {
    ...
}

Inside the constructor of MyMap I call the onCreate method
public MyMap() {
    ...
    this.onCreate(null);
    this.onResume();
    this.getMapAsync(this);
    ...
}

On my LG devices running Android 6 this throws the following exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources com.google.maps.api.android.lib6.impl.aq.e()' on a null object reference
at com.google.maps.api.android.lib6.gmm6.vector.ah.getResources(:com.google.android.gms.DynamiteModulesB:340)
at android.util.ResolutionOverride.<init>(ResolutionOverride.java:56)
at android.view.SurfaceView.init(SurfaceView.java:207)
at android.view.SurfaceView.<init>(SurfaceView.java:187)
at com.google.maps.api.android.lib6.gmm6.vector.am.<init>(:com.google.android.gms.DynamiteModulesB:1)
at com.google.maps.api.android.lib6.gmm6.vector.ah.<init>(:com.google.android.gms.DynamiteModulesB:3)
at com.google.maps.api.android.lib6.gmm6.api.am.<init>(:com.google.android.gms.DynamiteModulesB:53)
at com.google.maps.api.android.lib6.gmm6.api.am.a(:com.google.android.gms.DynamiteModulesB:49)
at com.google.android.gms.maps.internal.bv.a(:com.google.android.gms.DynamiteModulesB:38)
at com.google.maps.api.android.lib6.impl.az.a(:com.google.android.gms.DynamiteModulesB:80)
at com.google.maps.api.android.lib6.impl.az.a(:com.google.android.gms.DynamiteModulesB:1)
at com.google.maps.api.android.lib6.impl.cw.a(:com.google.android.gms.DynamiteModulesB:18)
at com.google.android.gms.maps.internal.t.onTransact(:com.google.android.gms.DynamiteModulesB:17)
at android.os.Binder.transact(Binder.java:387)
at com.google.android.gms.maps.internal.IMapViewDelegate$zza$zza.onCreate(Unknown Source)
at com.google.android.gms.maps.MapView$zza.onCreate(Unknown Source)
at com.google.android.gms.dynamic.zza$3.zzb(Unknown Source)
at com.google.android.gms.dynamic.zza$1.zza(Unknown Source)
at com.google.android.gms.maps.MapView$zzb.zzJy(Unknown Source)
at com.google.android.gms.maps.MapView$zzb.zza(Unknown Source)
at com.google.android.gms.dynamic.zza.zza(Unknown Source)
at com.google.android.gms.dynamic.zza.onCreate(Unknown Source)
at com.google.android.gms.maps.MapView.onCreate(Unknown Source)

I found a similar problem with Airbnb's react native map, but their solution does not seem relevant to my problem.
https://github.com/airbnb/react-native-maps/issues/1358
Any help or other ideas I could try out are much appreciated.

A: You can try to use MapFragment instead of MapView because for updated google play services 11.0.55 not supporting MapView.  I used MapView its worked for me.
Activity class:
    private SupportMapFragment mMapFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //return inflater.inflate(R.layout.fragment_find_direction, container, false);
        View view = inflater.inflate(R.layout.fragment_find_direction, null, false);
        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map_fragment);
        mMapFragment.getMapAsync(this);
        mMapFragment = mapFragment;
        return view;
    }

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
mMapFragment.onCreate(savedInstanceState);
}

Xml class:
<fragment
    class="com.google.android.gms.maps.SupportMapFragment"
    android:id="@+id/map_fragment"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/main_lay"
    android:apiKey="@string/google_map_key"
    android:clickable="true"
    android:enabled="true"
    android:focusable="true"
    app:layout_collapseMode="parallax">
</fragment>


text:
Q: Marquee of Images in android I m working on the showing of marquee of images in my project.
I had referred this example from github.
My Problem is, i m in need of showing the images only on the top of the screen not in the entire screen(like thumb images).
In that github example, they had used LinearLayout for showing the images which is scrolled automatically.
In my case the images are dynamic , i have to retrieve them from the database.
The total of number images size may vary.
My problem is when i have reached the last image, auto scroll stops , Also if i have only two images, it won't scroll.
So i m keen to know, is there any other way to achieve marquee of images in android.


text:
Q: how to calculate sum and term of recurring series involving Floor The recurrence series is given by
$$ t_{n+1} = t_n + 2\left\lfloor{n -1 \over 4} +1\right\rfloor , \; t_0 = 1$$
What would be the closed form of $t_n$ in terms of $n$ and it's sum up to $n$ terms?
The sequence generated can be found on here on OEIS.

A: First note that the sequence of $2\lfloor \frac{n-1}{4} + 1 \rfloor$ is
$$2, 2, 2, 2, 4, 4, 4, 4, 6, 6, 6, 6, \dots$$
For any integer $n$, let $k$ be the largest integer such that $4k \leq n$. In other words, $k=\lfloor \frac{n}{4}\rfloor$.
First we sum over the first $4k$ terms which gives us
$$ 4\times 2 + 4\times 4 + \dots + 4\times 2k = 8(1+2+\dots + k) = 4k(k+1)$$
Next let's add the remaining terms from $4k+1$ to $n$. There are $n-4k$ terms,each of them being $2(k+1)$. So the final result is
$$4k(k+1)+2(n-4k)(k+1)+1$$
where the last value of $1$ comes from the initial value $t_0=1$.

A: Ignore $t_0$ and $t_1$, the first terms $-1$ are: $\;(1\cdot2)\;(2\cdot2)\;(3\cdot2)\;(4\cdot2)\;(3\cdot4)\;(4\cdot4)\;(5\cdot4)\cdots$ which suggests:$$t_{n}=2{\lfloor\frac{n-1}{4}+1\rfloor}\cdot \left(n-1-2\lfloor\frac{n-1}{4}\rfloor\right)+1$$
(this looks more complicated than it actually is)
Note that when $n$ is a multiple of $4$ we have $\lfloor\frac{n-1}{4}\rfloor=\lfloor\frac{n}{4}-1\rfloor$ and otherwise $\lfloor\frac{n-1}{4}\rfloor=\lfloor\frac{n}{4}\rfloor$
$\bullet\;\;n$ multiple of $4:$
$$t_{n+1}=2{\lfloor\frac{n}{4}+1\rfloor}\cdot \left(n-2\lfloor\frac{n}{4}\rfloor\right)+1=2{\lfloor\frac{n}{4}\rfloor}\cdot \left(n-2\lfloor\frac{n}{4}\rfloor\right)+n+1$$
$$=2{\lfloor\frac{n}{4}\rfloor}\cdot \left(n-2\lfloor\frac{n}{4}\rfloor\right)+2{\lfloor\frac{n}{4}\rfloor}\cdot 2+1=2{\lfloor\frac{n}{4}\rfloor}\cdot \left(n+2-2\lfloor\frac{n}{4}\rfloor\right)+1$$
$$=2{\lfloor\frac{n}{4}\rfloor}\cdot \left(n-1-2\lfloor\frac{n}{4}-1\rfloor\right)+2\lfloor\frac{n}{4}\rfloor+1$$$$=2{\lfloor\frac{n-1}{4}+1\rfloor}\cdot \left(n-1-2\lfloor\frac{n-1}{4}\rfloor\right)+2\lfloor\frac{n-1}{4}+1\rfloor+1$$
$$=t_n+2\lfloor\frac{n-1}{4}+1\rfloor$$
$\bullet\;\;n$ not a multiple of $4:$
$$t_{n+1}=2{\lfloor\frac{n}{4}+1\rfloor}\cdot \left(n-2\lfloor\frac{n}{4}\rfloor\right)+1=2{\lfloor\frac{n-1}{4}+1\rfloor}\cdot \left(n-2\lfloor\frac{n-1}{4}\rfloor\right)+1$$
$$=2{\lfloor\frac{n-1}{4}+1\rfloor}\cdot \left(n-1-2\lfloor\frac{n-1}{4}\rfloor\right)+2\lfloor\frac{n-1}{4}+1\rfloor+1=t_n+2\lfloor\frac{n-1}{4}+1\rfloor$$
This verifies our assumption. The sum was nicely done by Patrick Li so I'll leave it there.


text:
Q: session based authentication in next.js with express-sessions hello i am trying to implement session based authentication for my next.js custom server express app .when i login session is set and it work as the way i expected but after few seconds or few request it don't. when i console.log(req.session) session is present but req.session.isLoggedin is disappeared.I want to implement session base authentication with database.
////server.js
/SOME NEXT.JS CUSTOM SERVER CODE/

app.prepare().then(() => {
  const session = require('express-session');
  const bodyParser = require('body-parser');
  const Mongodbstore = require('connect-mongodb-session')(session);

  const mongodburl = 'MONGODB_URL';
  const server = express();
  const store = new Mongodbstore({
    uri: mongodburl,
    collection: 'sessions',
  });

  server.use(bodyParser.urlencoded({ extended: false }));
  server.use(
    session({
      secret: 'VggyuvyhfSvcj',
      name: 'sessionID',
      resave: false,
      saveUninitialized: false,
      cookie: {
        maxAge: 100000,
        sameSite: 'strict',
        secure: false,
      },
      store: store,
    })
  );
  server.post('/', (req, res, next) => {
    const { user, password } = req.body;
    if (user === 'hello') {
      req.session.isLoggedin = true;
      return res.redirect('/home');
    }
    return res.redirect('/');
  });

  server.post('/logout', (req, res, next) => {
    req.session.destroy((err) => {
      if (err) {
        console.log(err);
        return res.redirect('/home');
      }
      res.clearCookie('sessionID');
      return res.redirect('/');
    });
  });

  server.all('*', (req, res) => {
    return handle(req, res);
  });
/SOME NEXT.JS CUSTOM SERVER CODE/

//// page/home.js
export default function Home() {
  return (
    <>
      <Logo />
      <Nav />
      <div className="body">
       HOME
      </div>
      <Foot />
    </>
  );
}

export async function getServerSideProps(contex) {
  const { req, res } = contex;
  console.log(req.session);
  if (!req.session.isLoggedin) {
    return { redirect: { destination: '/', permanent: false } };
  }
  return {
    props: {
      user: 'USER1',
    },
  };
}

console.log
Session {
  cookie: {
    path: '/',
    _expires: 2021-05-15T05:03:12.921Z,
    originalMaxAge: 100000,
    httpOnly: true,
    secure: false,
    domain: null,
    sameSite: 'strict'
  },
  isLoggedin: true
}

after few seconds or request
Session {
  cookie: {
    path: '/',
    _expires: 2021-05-15T05:03:27.188Z,
    originalMaxAge: 100000,
    httpOnly: true,
    sameSite: 'strict',
    secure: false
  }
}

i don't know why isLoggedin is disappeared after few request. but session is present in database and cookie in browser.


text:
Q: Calculate end rotation drawing circles I have one circle, which grows and shrinks by manipulating the radius in a loop.
While growing and shrinking, I draw a point on that circle. And within the same loop, increasing the angle for a next point.
originally it's written in JS, but I guess the math /theory will be the same
The setup is like this:

*

*radius = 0;

*circleAngle = 0;

*radiusAngle = 0;

*speed = 0.02;

*radiusSpeed = 4;

*circleSpeed = 2;

Within the loop, I update the angle for both the circle and the drawing line:
radius = Math.cos(radiusAngle) * 100;

// creating new point for line
let pointOnCircle = {
    x: Math.cos(circleAngle) * radius,
    y: Math.sin(circleAngle) * radius
};

circleAngle += speed * circleSpeed;
radiusAngle += speed * radiusSpeed;

Within this same loop, I draw the circle with radius as the radius. And draw a point with x and y position of pointOnCircle.x and pointOnCircle.y
Now, after unknown times of rotation, the drawing line is back to where it started, closing the path perfectly. And depending on the settings, some type of pattern / flower thing is drawn. This unknown times of rotations is what I want to calculate.
A working example can be found here: http://codepen.io/anon/pen/RGKOjP
While playing with the variables radiusSpeed and circleSpeed I logged the angles and checked when the line was back at the beginning again.
The results are as following. Where the first number is the variable radiusSpeed, the second is circleSpeed. The results are radiusAngle and circleAngle in degrees, at the moment the line comes back to its beginning:

*

*1, 1: 180, 180

*1, 2: 360, 720

*1, 3: 180, 540

*1, 4: 360, 1440

*1, 5: 180, 900

*2, 1: 720, 360

*2, 2: 180, 180

*2, 3: 720, 1080

*2, 4: 360, 720

*2, 5: 720, 1800

*3, 1: 540, 180

*3, 2: 1080, 720

*3, 3: 180, 180

*3, 4: 1080, 1440

*3, 5: 540, 900

I would like to calculate the rotations needed for the line to come back at the beginning and closing the path.
There clearly is a pattern in the outcome. But I can't figure it out.

A: You've got a curve given in polar coordinates $(r,\theta)$, where $r$ and $\theta$ are both periodic functions of some parameter $t$. To reduce clutter, let's take the maximum radius to be $1$ instead of $100$, since that's not going to change when or how often the curve returns to its starting point, which will then be $r=1$ and $\theta=0$.
The polar angle $\theta$ is just swept out at a constant rate: $$\theta(t)=\omega_1t\tag{1}$$ where $\omega_1=$speed * circleSpeed. We also have the radiusAngle being swept out at a (possibly different) constant rate: $\phi(t)=\omega_2t$, with $\omega_2=$speed * radiusSpeed. The radius thus varies sinusoidally: $$r=\cos{\phi(t)}=\cos{\omega_2t}.\tag{2}$$ Eliminating $t$ from these equations gives $$r=\cos{{\omega_2\over\omega_1}\theta}.\tag{3}$$
For this to represent the same point as the starting point, we must have $\theta=2n\pi$ ($n\in\mathbb Z$) and $r=1$, or, since $r$ can be negative, $\theta=(2n+1)\pi$ and $r=-1$. Plugging the first condition into (3), we get $$\cos\left({2{\omega_2\over\omega_1}n\pi}\right)=1 \\ 2{\omega_2\over\omega_1}n\pi = 2m\pi \\ {\omega_2\over\omega_1}n = m$$ for some integers $m$ and $n$. This can only hold if the ratio $\omega_2/\omega_1=$radiusSpeed / circleSpeed is rational, which it is in all of the cases that you tried. If we express this ratio in lowest terms as $p/q$, we get $pn=qm$, so we can find the smallest positive $n$ and $m$ for which this holds by computing the LCM of $p$ and $q$.
Turning to the second possibility, $$\cos{\left({\omega_2\over\omega_1}(2n+1)\pi\right)}=-1 \\ {\omega_2\over\omega_1}(2n+1)\pi=(2m+1)\pi \\ {\omega_2\over\omega_1}(2n+1)=2m+1.$$ As before, we can rewrite this as $p(2n+1)=q(2m+1)$, which is similar to the previous equation except that both factors have to be odd.
So, to find the recurrence angles $\theta$ and $\phi$, start by expressing radiusSpeed / circleSpeed in lowest terms as $p/q$ and find the LCM of the numerator and denominator. Divide this number by $p$ and $q$, respectively, to get the values $a$ and $b$. If these two numbers are both odd, then $\theta=\pi a$ and $\phi=\pi b$, otherwise $\theta=2\pi a$ and $\phi=2\pi b$.
As a sanity check on this formula, we can see that it is consistent with some of the patterns in your data: the results are symmetric, in that swapping the two speeds also swaps the angles; all of the cases in which the two speeds are equal have the same angles; and cases 1,2 and 2,4 also have the same angles.


text:
Q: How to replace ASCII code (alt+207) in JavaScript? I have a string which contains square boxes(I found it's ascii code as alt+207)...
How can I replace this with ' '(a single space).

A: I am assuming you mean the character: ¤
If so, you could try,
str = str.replace('\u00A4', ' ');

Or if you want to do it to any character that is not ASCII, you could try something like:
str = str.replace(/[^\u000A\u0020-\u007E]/g, ' ');

A: Is it one of these characters? ▪ = ▪ or ■ = ■
If so, you can do this
var str ="Something ▪ and ■";
str = str.replace(/▪|■/g, " ");
document.write(str);

http://jsfiddle.net/jasongennaro/8mCuV/


text:
Q: Where does the minus sign go on Givens rotations? I've been reading about using Givens rotations for QR factorization, but I've come across a small inconstancy between all of my resources. Some give a basic Givens matrix as
$$\begin{bmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{bmatrix}$$
while others
$$\begin{bmatrix}\cos\theta&\sin\theta\\-\sin\theta&\cos\theta\end{bmatrix}$$
And it never seems to be explained if it matters which sine is negated. Does it matter? Is it a case-by-case thing where you have to figure it out as you do it? What is the rule?
Thanks for input!


text:
Q: IndexError: list index out of range in Tensorflow chatbot
import random
import json
import pickle
import numpy as np

import nltk
from nltk.stem import  WordNetLemmatizer

from tensorflow.keras.models import load_model

lemmatizer = WordNetLemmatizer()
intents = json.loads(open('intents.json', encoding='utf-8').read())

words = pickle.load(open('words.pkl', 'rb'))
classes = pickle.load(open('classes.pkl', 'rb'))
model = load_model('chatbot.model')

def cleanSentance(sentence):
    sentence_words = nltk.word_tokenize(sentence)
    sentence_words = [lemmatizer.lemmatize(word) for word in sentence_words]
    return sentence_words

def bagOfWords(sentence):
    sentence_words = cleanSentance(sentence=sentence)
    bag = [0] * len(words)
    for w in sentence_words:
        for i, word in enumerate(words):
            if word == w:
                bag[i] = 1
    return np.array(bag)

def predict_class(sentence):
    bow = bagOfWords(sentence)
    res = model.predict(np.array([bow]))[0]
    errThresh = 0.25
    results = [[i, r] for i, r in enumerate(res) if r > errThresh]

    results.sort(key=lambda x: x[1], reverse=True)
    return_list = []
    for r in results:
        return_list.append({'intent': classes[r[0]], 'probability': str(r[1])})
    print(return_list)
    return return_list

def getResponse(intents_list, intents_json):
    tag = intents_list[0]['intent']
    list_of_intents = intents_json['intents']
    for i in list_of_intents:
        if i['tag'] == tag:
            result = random.choice(i['responses'])
            break
    return result

print("Type below")

while True:
    message = input("->")
    ints = predict_class(message)
    print(ints)
    print(intents)
    response = getResponse(ints, intents)
    print(response)

When I type something, it comes up with the error:
***Traceback (most recent call last):
  File "C:\Users\myusrname\Documents\pythonProject\ArthurAI.py", line 61, in <module>
    response = getResponse(ints, intents)
  File "C:\Users\myusrname\Documents\pythonProject\ArthurAI.py", line 46, in getResponse
    tag = intents_list[0]['intent']
IndexError: list index out of range***

Again, I've been following this tutorial: https://www.youtube.com/watch?v=1lwddP0KUEg
Also, when training the model (I asked for help with it here: ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list)), the accuracy was all 1, not 0.87453 or 0.98745, just 1, for all the epochs. Is that a good thing?
Inputs include "hello", "how are you" or anything in the intents.json file

A: You can do this by changing the code at the end:
while True:
    message = input("->")

    try:
        ints = predict_class(message)
        print(ints)
        print(intents)
        response = getResponse(ints, intents)
        print(response)

    except IndexError:
        print("What?")

It will try to answer, if can't answer, it will ask again.


text:
Q: How to set background image for portrait video? I have been trying to set background image/CALayer for portrait video so that I can avoid black bars.
I could set image but it shows black background instead of image.
CALayer *videoLayer = [CALayer layer]
CGRect frame = CGRectMake(0, 0, size.with, size.height);
videoLayer.frame = frame;
videoLayer.backgroundColor = [UIColor clearColor].CGColor;
CALayer *backgroundImageLalyer = [CALayer layer]
CALayer *outputLayer = [CALayer layer]
[outputLayer addSublayer:backgroundImageLayer]
[outputLayer addSublayer:videoLayer]

[backgroundLayer setContents:(id)[backgroundImage CGImage]];
backgroundLayer.frame = frame;
[backgroundLayer setMasksToBounds:YES];

composition.animationTool = [AVVideoCompositionCoreAnimationTool
                               videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:outputLayer]

Can anyone please suggest me to set background image for portrait videos?


text:
Q: Chow ring of $E_7$ varieties Consider a split algebraic group $G$ of type $E_7$ over a field of characteristic zero.
It is known that some subgroups $P_i$ of $G$, which are called parabolic, have the property that the object $G/P_i =:X_i$ is a projective, homogeneous variety over $k$.
These parabolic subgroups correspond to subsets of nodes in the Dynkin diagram of $G$.
We use Bourbaki enumeration. We write Ch$(X)$ for the Chow ring of $X$ modulo rational equivalence and with $\mathbb{F}_2$ coefficients.
Question: What is the structure of Ch$(X_3)$ ?
I can find references for $X_1$ and $X_7$, but for the Chow ring of $X_3$, which is probably way more complicated, i cant find any results.
It would already be great to know how many generators there are and what their dimension is.


text:
Q: Convert Date time to UTC Time in python I have datetime value in format of 2022-01-26T07:01:36-08:00 (based on which user fetches data, it will have local timezone, like -08:00, +05:30)
I want to convert this time into UTC Time.
I saw multiple example of pytz but couldn't figure out how to convert using pytz or datetime. datetime value will be based on machine timezone so I can't hard code timezone value also.


text:
Q: momentjs subtract get Nature month error I used subtract function to get Nature month, but it's not work. following is my code
var month = moment('2013-12-31').subtract('month',1);

I want result is 2013-12-01 but it response 2013-11-30.
I don't know what wrong with it?
Anyone can help me?
Thanks!

A: you are subtracting the month from the date and expecting the result from the same month. it seems like moment is working fine. if you want that result add one more day to the response.
try this
var month = moment('2013-12-31').subtract('month',1).add('days',1);

This will subtract one month from the data and add one day to so you will get the correct response. that is first of that month.


text:
Q: Best Linux OS for 64GB ram server What is the best Linux OS (server) that can make full utilization of a 64GB ram server machine.?

A: Memory utilization is handled by the kernel, which is common to all of the distros. Tuning can differ between the distros, but in my experience it doesn't vary much at all. 64-bit Linux doesn't consider 64GB to be a very large amount, at least with newer kernels, so they all should handle it very, very similarly. Even the Enterprise distros (RHEL, SLES, OUL) which are running older kernels have patches to make sure their memory management is top notch, as they're even more likely than Ubuntu et. al. to run in high-RAM environments.
In the end, the "best 64-bit distro" is whichever Linux distro you like to work with best. The technical differences are slight at best.

A: It depends on what you're the most familiar with, it'd have to be 64bit, in any case. For example, I would choose Ubuntu because I know the platform and I feel comfortable with the way things are done. Debian would be my second choice if stability was my main concern, but if I was looking for something bleeding edge I'd go with Fedora.
They can all make equal (read: full) utilization of 64GB of RAM because they're all Linux and memory limits happen in kernel-space, not user-space.

A: I suggest for the same is Cent OS 64 bit version you can use :)

A: I suggest Cent Os,because The first thing I noticed with Cent Os was a speed increase. The new 2.6.9 kernel, newer packages, and general improvements seem to have boosted performance, especially of the proxy server. On the same hardware, Squid was using less memory and CPU time, and was working faster.The key advantages of CentOS over other linux-type distributions, apart from its free nature, is its rock-solid reliability and the long lifecycle of the product.


text:
Q: Weka command line attributes arguments On the command line, I'm able to get this rolling with no problem:
java weka.Run weka.classifiers.timeseries.WekaForecaster -W
"weka.classifiers.functions.MultilayerPerceptron -L 0.01 -M 0.2 -N 500 -V 0 -S 0 -E 20 -H 20 " -t "C:\MyFile.arff" -F DirectionNumeric  -L 1 -M 3 -prime 3 -horizon 6 -holdout 100 -G TradeDay -dayofweek -weekend -future

But once I try to put the skip list, I start to get errors saying that it's missing a date that is not in the skip list even though the date is in fact on it:
java weka.Run weka.classifiers.timeseries.WekaForecaster -W "weka.classifiers.functions.MultilayerPerceptron -L 0.01 -M 0.2 -N 500 -V 0 -S 0 -E 20 -H 20 " -t "C:\MyFile.arff" -F DirectionNumeric  -L 1 -M 3 -prime 3 -horizon 6 -holdout 100 -G TradeDay -dayofweek -weekend -future -skip ""2014-06-07@yyyy-MM-dd, 2014-06-12"
Does anybody knows how to get this working? Weka is low on documentation as far as I know.
Thank's in advance!

A: Forget it.  I got it, the problem was the 's' must be in capital letters:
-Skip
instead of
-skip.


text:
Q: undefined control sequence  \textminus in listing I tried to insert python code in my LaTeX document for a project of mine. For this, I used the listings package. For some reason unknown to me, a minus sign in my python code throws an

!undefined control sequence
argument \textminus
l.158 for i in range(len(res)-1):
The control sequence at the end of the top line
of your error message was never \def'ed.

I have been able to reproduce the error using the simple code (not showing my entire code as it's quite long, but kept the same parameters for listings):
\documentclass[12pt,a4paper,final]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{fancyhdr}
\usepackage{stackengine}
\usepackage{listings}
\usepackage{xcolor}
\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}

\definecolor{codeorange}{rgb}{1,0.5,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codeyellow}{rgb}{0.9,0.9,0}

\lstdefinestyle{pythonsub}{
    commentstyle = \color{codegray},
    keywordstyle = \color{codeorange},
    stringstyle = \color{codeyellow},
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize = 4,
}

\parindent 0ex
\lstset{style=pythonsub}

\begin{lstlisting}[language=Python]
 one = 2-1
\end{lstlisting}

simply removing the minus sign in my python code (see below) resolves the issue, but of course then it's not the same code.
\begin{lstlisting}[language=Python]
 one = 21
\end{lstlisting}

other similar characters (+, =, /,...) don't cause any problem. What's the best way to resolve this error?
In case it matters, I'm using TeX maker with MikTeX  2.9.6930 64-bit installed.


text:
Q: System of coupled differential equations I have the following system of three linear differential equations that I need to solve numerically using finite diferences:
$$\begin{aligned}
\frac{dn_0}{dt} &= -n_0(t)W_{01}(t) + n_1(t)K_{10}\\
\frac{dn_1}{dt} &= -n_1(t)W_{12}(t) - n_1(t)K_{10} + n_2(t)K_{21} + n_0(t)W_{01}(t)\\
\frac{dn_2}{dt} &= n_1(t)W_{12}(t) - n_2(t)K_{21}
\end{aligned}$$
where the boundary conditions are
$$ n_0(0)=1 $$
$$ n_0(N)=0 $$
$$ n_1(0)=0 $$
$$ n_1(N)=1 $$
$$ n_2(0)=0 $$
$$ n_2(N)=0 $$
The three equations are restricted by $n_0 + n_1 + n_2 =1$, I tried to replace and write the equations, in an attempt to
$$\frac{dn_0}{dt} + \frac{dn_1}{dt} +\frac{dn_2}{dt} = 0$$
Since I can not use the finite difference method for coupled equations,thinking that as a solution the values of the derivatives should be equal to zero, so I could just rewrite one of the equations by isolating the variables, but I'm not sure about that. Does anyone know a way or some technique that I can decouple the 3 equations?

A: The system is a linear time-variant system. We can write it in matrix form as
$$\dfrac{d}{dt}\begin{bmatrix}n_0 \\ n_1\\ n_2 \end{bmatrix}=
\begin{bmatrix}
-W_{01}(t) & K_{10} & 0\\
W_{01}(t) & -K_{10}-W_{12}(t)&K_{12}\\
0 & W_{12}(t) & -K_{21}\\
\end{bmatrix}\begin{bmatrix}n_0 \\ n_1\\ n_2 \end{bmatrix}.$$
Then we have $n_0=1-n_1-n_2$. This invariant allows us to remove the line of the equation. Because if we know $n_1$ and $n_2$ we can simply calculate $n_0$. If we substitute this invariant into the second and third line we obtain.
$$\dfrac{d}{dt}\begin{bmatrix} n_1\\ n_2 \end{bmatrix}=
\begin{bmatrix}
-K_{10}-W_{12}(t)-W_{01}(t) &K_{12}-W_{01}(t)\\
W_{12}(t) & -K_{21}\\
\end{bmatrix}\begin{bmatrix} n_1\\ n_2 \end{bmatrix}+\begin{bmatrix}W_{01}(t)\\0 \end{bmatrix}.$$
Can you supply more information on $W_{12}(t)$ and the other terms? In general, it will be problematic to help you to decouple both equations. But you should be able to solve this coupled system without any problems with numerical solvers for differential equations.


text:
Q: Why $\sum_{k=1}^{\infty}\frac{\ln(k)}{k}$ diverges? So my solution manual says this diverges since it is a p-series and $p=1 \le 1$
I understand why that p-series converges, but I don't understand conceptually how they got there using the comparison test (as the instructions advise).
Again, here is my series:
$$\sum_{k=1}^{\infty}\frac{\ln(k)}{k}$$
The instructions used the following comparison:
$$\frac{\ln(k)}{k} \gt \frac{1}{k}$$
This is what confuses me about this problem and the solution.  Why was the above comparison used?  I understand the concept that if $a_n \lt b_n$ and $b_n$ converges then $a_n$ converges.
This makes sense to me because I can see a graph in my head of a larger series converging so the smaller similar series must also converge.
Is the above comparison checking to see if the smaller series diverges and if so the larger must also diverge?
Please help me to understand this.

A: It is also true that if $a_n > 0, \quad b_n \gt 0$, $\sum a_n$ diverges and $a_n < b_n $, then $\sum b_n$ also diverges.
Here, we are comparing
$$a_n = \dfrac{1}{n}\;\;\text{ and }\;\;b_n = \dfrac {\ln n}n$$ and we have:

*

*$a_n >0, b_n>0$

*$a_n$ diverges; (it's the harmonic series, which diverges;
you should make sure you know this - and if you haven't already
explored the proof of its divergence, do so!),

*$b_n > a_n$. So our series with the term $b_n$ diverges.

A: Recall that a series $\displaystyle\sum_{n\ge0} a_n$ is said to be convergent if the partial sum sequence $\displaystyle\left(\sum_{k=0}^n a_k\right)_n$ is convergent. Now use what you know about the sequences and the fact that the harmonic series is divergent.

A: For another approach to this problem you could use the Integral Test. Consider $$\int_1^\infty{\ln(x)\over x} dx.$$ If $u=\ln(x)$, then $du={1\over x} dx$. Which gives us $$\lim_{t\rightarrow \infty}\int_1^t{\ln(x)\over x}dx=\lim_{t\rightarrow \infty}{\ln(x)^2\over 2}|_1^t=\lim_{t \rightarrow \infty}{\ln(t)^2\over 2}=\infty.$$ Thus $$\sum_{k=1}^\infty{\ln(k)\over k}$$ is divergent. If the divergence of the Harmonic series is causing an issue check out this link, hopefully it can help How do I prove that the series $\sum_{n=1}^\infty \frac{1}{n}$ diverges?.

A: The comparison test that you would use for the convergence applies exactly the same when your series diverges, as seen on this article :
http://en.wikipedia.org/wiki/Convergent_series#Convergence_tests
So your reasoning is perfectly correct ;) !


text:
Q: Take PHP Debug mode off for CakePHP I did the CakePHP tutorial, but I get this

at the top and bottom. I would like to take that away.
And I have a question, when making a brand new app, do I have to deattach any css or stuff like that?

A: TLDR:
Remove stuff from View/Layouts/default.ctp (your default layout file)
Removing the code at the bottom:
In the View/Layouts/default.ctp (your default layout file), there is code at the bottom that shows the sql queries.  Just remove it, and you'll no longer have all that data printed at the bottom:
<?php echo $this->element('sql_dump'); ?>

(It's something that should be removed anyway if you plan on using DebugKit... which you should be planning on doing.)
Removing the style in general:
As for the style (colors...etc), if you also look in the same file, you'll see (toward the top) that it includes the generic CakePHP CSS.  Just remove this line to get rid of their generic styling:
echo $this->Html->css('cake.generic');

Removing the description of CakePHP:
Same file - just remove this:

<?php echo $this->Html->link($cakeDescription, 'http://cakephp.org'); ?>

A: Ensure you set your debug mode to false

in your config, app.php for cakephp3.x
'debug' => filter_var(env('DEBUG', false), FILTER_VALIDATE_BOOLEAN),

A: You can disable the debug feature by turning debug to 0 in the core.php file. Regarding your second question, what do you mean exactly with "dettach any css"?


text:
Q: Textbox description in RDLC I'm creating a RDLC report using Visual Studio 2013 and I'm using a lot of TextBox containing formulas.
Is there a way to display some different name for this TextBox instend of just <<Expression>> ? This way is not very clear since all the fields seems the same. I see TextBox have a Description field but it doesn't work for me, it only does if I use Placeholders


text:
Q: Sending ASCII character to server using Java I am trying to connect my computer with a device using Socket.
Using my code, I managed to connect to another device using socket.
The connection worked but the problem now is that the device that I am connected to have it's own SDK and it's in ASCII characters.
When I try to send in a command (from the SDK) using String, the code does not work, please advice.
String Address = txtAddress.getText();
    Socket MyClient;
    try {
        MyClient = new Socket(Address,9993);
        os = new DataOutputStream(MyClient.getOutputStream());
        is = new DataInputStream(MyClient.getInputStream());
        this.main.showUserView();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
         lble.setText("Don't know about host: hostname");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        lble.setText("Couldn't get I/O for the connection to: hostname");
    }

A: Maybe you can try to send data using DatagramPacket?
int PORT = ## (port we are using for communication)

byte[] strBytes = myString.getBytes();

InetAddress address = InetAddress.getByName(ipAddressString);
DatagramPacket packet = new DatagramPacket(strBytes, strBytes.length, address, PORT);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();


text:
Q: Stored Procedure, when to use Output parameter vs Return variable When would you use an output parameter vs a return variable, or vice versa? In the following simple example, I can achieve the same thing using either one.
Using output parameter
create proc dbo.TestOutput (@InValue int, @OutValue int output)
as
set @OutValue = @InValue

declare @x int
exec TestOutput @InValue = 3, @OutValue = @x output
select @x

Using return variable:
create proc dbo.TestReturn (@InValue int)
as
return @InValue

declare @x int
exec @x = TestReturn @InValue = 3
select @x

As you can see, they both do the same thing. Can someone show me an example where the choice of a output parameter vs a return variable would make a difference?

A: taken from here

*

*When you want to return one or more items with a data type then it is better to use an output parameter.

*Generally, use an output parameter for anything that needs to be returned.

*When you want to return only one item with only an integer data type then it is better to use a return value.

*Generally, the return value is only to inform success or failure of the Stored Procedure.

*A return List item a value of 0 indicates success and any non-zero value indicates failure.

A: I prefer:
Using a return value when you only need to return one item.
Using output parameters when you need to return more than one value.
Another common usage pattern, although not my preference, is to use return values only to inform of success or failure and output parameters for anything that needs to be returned.

A: This is T-SQL, not C. Never use return values, many client side APIs make dealing with return values a pain if not plain impossible. Always use OUTPUT parameters.

A: Since return values only work with int, it ends up being "inconsistent". I prefer the output param for consistency.
Also, output params force the caller to recognize the returned value. IME, return values are routinely ignored.

A: You should use RETURN to return a value from a procedure much in the same way you'd use EXIT to return a value in a batch script.  Return isn't really for parameter passing, but rather as a way to quit out of a procedure or query.  As per MSDN documentation:

Unless documented otherwise, all system stored procedures return a value of 0. This indicates success and a nonzero value indicates failure.

This becomes more evident once you recognize the lack of any ability to define a type to your return value.  It has to be INT.

A: I will answer this question in different ways:
If you would like to return one value you have both the options. But if you would like to return multiple values you only need to stick with output parameters.
Second Scenario: In C# you have the control of type if you are using output parameters.
Third scenario: Function vs. Procedure select the one suiting to your needs.
Hope this helps

A: I use return value to many things because it is more performative such as:
1 - When you insert or change an item when I do the validation in the database Return positive number to return the Identity and negative with the number of the error, it is faster.
2- When I make an appointment with paging use it to return the total amount of records is also faster and less costly.
For the rest I use Output when there are several returns or different types of int. And of course I use recorset to return a list of items
How do I use the Dapper to make my queries I do not suffer.


text:
Q: Haskell. Strict application $! I execute the next code:
(take 10) $! [1,2..]

What is it ? I thought, ghc  will yield a termination, beacause i say "evaluate [1,2..] force". But I got the result "[1,2,3,4,5,6,7,8,9,10]".

A: The forced evaluation will only ensure its argument [1,2..] isn't bottom.  [1,2..] matches (1:_), so it isn't bottom, and the computation will go on as expected, returning [1,2,3,4,5,6,7,8,9,10].
Not sure where you got that single 1 result from; would you mind copy-pasting an excerpt of a GHCi session?

A: Did you type something wrong?  It works for me with or without parentheses, under GHCi 6.8.2...
GHCi, version 6.8.2: http://www.haskell.org/ghc/  :? for help
($Loading package base ... linking ... done.
Prelude> take 10 $! [1..]
[1,2,3,4,5,6,7,8,9,10]
Prelude> (take 10) $! [1..]
[1,2,3,4,5,6,7,8,9,10]
Prelude> (take 10) $! [1,2..]
[1,2,3,4,5,6,7,8,9,10]

A: So you expect the list to be fully evaluated. ($!) is implemented in terms of seq, and seq "only" evaluates to head normal form according to the docs. It'll only make a difference if the value is undefined:
Prelude> take 0 undefined
[]
Prelude> take 0 $! undefined
*** Exception: Prelude.undefined

A function is strict in its argument if
f undefined = undefined

This does not imply that the argument is fully evaluated in an eager fashion. What you want is something like DeepSeq.
GHCi, version 6.10.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling DeepSeq          ( deepSeq.lhs, interpreted )
Ok, modules loaded: DeepSeq.
*DeepSeq> take 1 $!! [1,2,undefined]
*** Exception: Prelude.undefined
*DeepSeq>

Your example with $!! from DeepSeq runs forever.


text:
Q: Read CSV file in django Below is my code
read_csv.py
from www.models import Attendance , Employee

import csv
import datetime

dataReader = csv.reader(open('www/attendace.csv'), delimiter=',', quotechar='"')

dic = {}
for row in dataReader:
    if row[0] != 'Ac-No': # Ignore the header row, import everything else
        account_number = row[0]
        stime = row[2]
        if account_number not in dic:
            dic[account_number] = []

        dic[account_number].append(stime)

for acc, stimes in dic.iteritems():
    checkin = stimes.pop(0)
    print checkin
    employee = Employee.objects.get(acc_no= acc)
    print str(employee.acc_no)

    d = checkin[:-4].strip()
    check_in = datetime.datetime.strptime(d, "%m/%d/%Y %H:%M" )

    check_out = None
    for stime in stimes:
        stime = stime[:-4].strip()
        stime = datetime.datetime.strptime(stime, "%m/%d/%Y %H:%M" )

        if stime.date() == check_in.date():
            check_out = stime
            print check_out
        else:
            attend = Attendance()
            attend.check_in = check_in
            attend.check_out = check_out
            attend.employee = employee
            attend.save()
            check_in = stime
            check_out= None

I want to have for every account_number, check_in and check_out date, so I have dic with the employee account_number and the list of stime(check_in and check_out together).
The problem is I am getting the output only for 1 employee and its wrong, for example emp 1 has 3 records for checkin and checkout if I keep running employee 1 can have till 30 ..
can someone help ?


text:
Q: Invalid number during insert query Insert SQL:
INSERT INTO TB.SDL
  (
    SOL_ID,
    LOCKER_TYPE,
    LOCKER_NO,
    CUST_ID,
    STAFF_FLG,
    RENT_AMOUNT_CHARGED,
    PERCENT_RENT,
    START_DATE,
    LCHG_TIME,
    LCHG_USER_ID,
    RCRE_TIME,
    RCRE_USER_ID,
    DEL_FLG,
    BANK_ID
  )
  VALUES
  (
    '42' ,
    'KUK' ,
    'KU19' ,
    '00080' ,
    'N',
    '49.50' ,
    '33,33',
    sysdate,
    sysdate,
    'AAY' ,
    sysdate,
    'AAY' ,
    'N',
    '01'
  );

Error:

-ORA-01722:Invalid Number

INSERT INTO TB.SDL
  (
    SOL_ID,
    LOCKER_TYPE,
    LOCKER_NO,
    CUST_ID,
    STAFF_FLG,
    RENT_AMOUNT_CHARGED,
    PERCENT_RENT,
    START_DATE,
    LCHG_TIME,
    LCHG_USER_ID,
    RCRE_TIME,
    RCRE_USER_ID,
    DEL_FLG,
    BANK_ID
  )
  VALUES
  (
    '42' ,
    'KUK' ,
    'KU19' ,
    '00080' ,
    'N',
    49.50 ,
    '33,33',
    sysdate,
    sysdate,
    'AAY' ,
    sysdate,
    'AAY' ,
    'N',
    '01'
  );

Table description:

-1 Row inserted

I want to insert 33,33 in percent_rent column but it doesnt let me do so .
Can any please why case1 is failing ?I have inserted the column description image as well.

A: Your table description shows that the column PERCENT_RENT is NUMBER(9,6) data type. The problem is that you are inserting the value '33,33' which is  a string and not a number.
Insert the number as it is, no need of single-quotation marks.
For example,
SQL> CREATE TABLE t(A NUMBER(9,6));

Table created.

SQL> INSERT INTO t(A) VALUES(33.33);

1 row created.

SQL> COMMIT;

Commit complete.

I want to insert 33,33 in percent_rent column but it doesnt let me do so

The format is controlled by NLS_NUMERIC_CHARACTERS parameter.
You could specify it at session level or at individual SQL level.
If you want to insert the number in your desired format, then you must use TO_NUMBER.
For example,
SQL> INSERT INTO t (a)
  2    VALUES
  3    (
  4      TO_NUMBER('33,33','9G999D00', 'NLS_NUMERIC_CHARACTERS = '',.''')
  5    );

1 row created.

 SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

         A
----------
     33,33

Now, to display the number in your desired format, use TO_CHAR.
For example,
SQL> SELECT TO_CHAR(A,'9G999D00', 'NLS_NUMERIC_CHARACTERS = '',.''') my_number_format
  2  FROM t;

MY_NUMBER
---------
    33,33

A: In addition to the above answers... You represent RENT_AMOUNT_CHARGED with a period for the decimal marker while PERCENT_RENT uses a coimma. Both in a string, but only one can be converted to a number as shown in the output you get in the error.
Why not just try putting a period in the pct just to try the suggestion? Setting NLS_NUMERIC_CHARACTERS will not help as long as you have different makers for it in your two strings. You have to chose one way to specify your decimal point.


text:
Q: Import Shapefile to Postgres I am trying to import a shapefile to Postgres using the following:
shp2pgsql c:\location\water_areas.shp water > water.sql

I am receiving the following message:
c:\location\water_areas.shp: shape (.shp) or index file (.shx) can not be opened, will just import attribute data.

Unfortunately I need more than just attribute data. I need the geometry column. Please help. Why won't it open the shapefile for the conversion.

A: Without any extra information, there's no way to answer your question. The error message is indicating the app is not finding one or more of the file components. Try running the app inside the 'location' directory with a relative path and see if that changes.


text:
Q: Why wont the code below execute when a cell is double clicked on? The code below ran earlier but will not execute when a cell is double clicked.
Private Sub Worksheet_DoubleClick(ByVal Target As range, Cancel As Boolean)
    If Target.Font.Bold = False Then

            Target.Font.Bold = True
            Target.Font.Color = vbRed
    Else
            Target.Font.Bold = False
            Target.Font.Color = 1

    End If
End Sub

A: DO NOT type any of these signatures manually!
Use the code pane dropdowns instead:

Select Worksheet from the left dropdown, and pick an event to handle in the right dropdown; the VBE will generate a method stub with the proper signature for you.
Typing them out manually off the top of your head can (and does!) result with handlers that end up never being called, or worse, that are called, but are given parameter values in the wrong arguments, e.g. if UserForm_QueryClose is typed up manually with inverted parameters (the handler has 2 Integer parameters, so you need to remember the exact order.. otherwise you assign Cancel and the form understands that you assigned CloseMode)
If you're not seeing Worksheet in the left dropdown, then you're not in a worksheet's code-behind module. Worksheet events can only be handled in a worksheet module.
In a Workbook module (i.e. ThisWorkbook) you can handle the SheetBeforeDoubleClick event to handle a double-click on any worksheet in the workbook:
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)

End Sub

A: Not an answer to why it's not working (@Mat's Mug and @Scott Craner beat me to that again), but a shortened version of the code.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

    With Target.Font
        .Bold = Not .Bold
        .Color = Choose(Abs(CLng(.Bold)) + 1, 1, vbRed)
    End With

End Sub

Ok, not as easy to follow as the original but here's what it's doing:
Target.Font.Bold is either TRUE or FALSE, so Not .Bold will return the opposite.
Bold = TRUE so Not Bold = FALSE
Abs(CLng(.Bold)) + 1
Again, .Bold is either TRUE or FALSE.  Numerically TRUE = -1, FALSE = 0.
CLNG(.Bold) will return -1 or 0.
ABS(CLNG(.Bold)) will return 1 or 0.
Abs(CLng(.Bold)) + 1 will return 1 or 2 - which is used in the CHOOSE command to return vbRed or 1.


text:
Q: Jquery .change() function doesnt`work on localhost The following code works on jsfiddle but does not work on localhost, can you help me please?

     <form>
      <input class="puankontrol" type="text" name="puan"/>

      <input class="puankontrol" type="text" name="puan"/>

      <input class="puankontrol" type="text" name="puan"/>

    </form>

      Trigger the handler

`

A: Try
$(document).ready(function(){
   //change function declaration.
});

also use


text:
Q: Change Structure Permalink => Error 404? How to redirect i have a problem with Permalink as:
former, i have set Structure Permalink as: /abc-%postname%/ now i change (remove abc-) and set Structure Permalink to Post name as /%postname%/ but all my link is error 404.
Any idea for auto redirect Permalink /abc-%postname%/ to /%postname%/
Thank you very much.

A: You can use a rule in your .htaccess (a file that will be in the root folder of your WordPress installation) - add this to the very bottom:
RewriteEngine On
RewriteRule ^/?abc-(.+)/?$ /$1/ [R=301,L]


text:
Q: Redis key matching performance We are using Redis for key-value ordinary caching and for our thumbnail cache. In a machine which has 100+ sites Redis thumnail database has 500000 keys without distinctive prefix like:
"sorl-thumbnail||image||6c4a67b016c4f867b9fdd3e5c5609887"
"sorl-thumbnail||image||ad7c56bd5461e9061604867d056b5de8"
"sorl-thumbnail||image||655ad6bb21129326ef4618df83a0f1f7"
"sorl-thumbnail||thumbnails||871641bfefa6250518fe52b86cf742c9"
"sorl-thumbnail||thumbnails||570565770557013bada8c1fe2cb3d658"
"sorl-thumbnail||image||c01134f4a8746d24c6d62543419bbb3a"
"sorl-thumbnail||image||ecc5afb281bc78fefe3046e2cc3f972a"
"sorl-thumbnail||image||670f1f1b6c5660f46053a484e22a4071"

Does using a prefix like 001,002,003,... 100 for site ids increase the performance  of accessing Redis?

A: Because the data structure of the main dictionary is a hash table and not a tree, the general performance of Redis is not really impacted if you have plenty of keys with a common prefix.
Prefixing your keys with some discriminating data will not really improve performance.


text:
Q: How to get total number of table elements having ID inside a DIV tag using Selenium Webdriver and C# How can I get the total number of table elements having ID inside a DIV tag using Selenium Webdriver and C#?
Expected Output: I need output as "Number of Table ID = 2 "
 <form id="form1">

 Item Details

</form>

A: Try like this:
WebElement webElement = driver.findElement(By.xpath("//form[@id='form1']/div[4]"));

//Get list of table elements using tagName
List<WebElement> list = webElement.findElements(By.tagName("table"));

A: XPath:
IList<IWebElement> tableIDs = driver.FindElements(By.XPath("//div/table[@id]"));

Console.WriteLine("Number of Table ID = {0}", tableIDs.Count);

Css:
IList<IWebElement> tableIDs = driver.FindElement(By.CssSelector("div>table[id]"));

Console.WriteLine("Number of Table ID = {0}", tableIDs.Count);


text:
Q: C++: Accessing the parent class from a child-class I have two classes:
class ClassA {
    public:
        ClassB *classB;
        int i = 100;
}
// and:
class ClassB {
    public:
        void longProcess();
}

I run a void from ClassB():
ClassA classA = new ClassA();
classA->i = 100;
classA->classB = new ClassB();
classB->longProcess(); // it's a long process!
// but when it will finish - I need to get the "i" variable from ClassA

How do I get the "int i" variable from the method: longProcess()? Actually, I need to running this long code in another thread that's why I need to retrieve the "i" variable from the ClassB when the longProcess() will finished its work. Any suggestions?
Update: I try to write some code for saving the pointer to the parent class
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=[ ChildClass.h ]-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "ParentClass.h"
class ChildClass {
    public:
        ChildClass();
        ParentClass *pointerToParentClass; // ERROR: ISO C++ forbids declaration of 'ParentClass' with no type
        void tryGet_I_FromParentClass();
};

ERROR: ISO C++ forbids declaration of 'ParentClass' with no type
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=[ ChildClass.cpp ]-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "ChildClass.h"
ChildClass::ChildClass(){}
void ChildClass::tryGet_I_FromParentClass(){
    // this->pointerToParentClass...??? it's not work
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=[ ParentClass.h ]-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "ChildClass.h"
class ParentClass {
    public:
        ParentClass();
        ChildClass *childClass;
        int i;
};

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=[ ParentClass.cpp ]-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "ParentClass.h"
ParentClass::ParentClass(){
    childClass = new ChildClass();
    childClass->pointerToParentClass = this;
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=[ MainWindow.cpp ]-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
ParentClass *parentClass = new ParentClass();

A: You need to pass the this pointer from class A (or any pointer to it) to Class B (probably in the constructor) so that it knows where it's contained in, and probably have a member of class B that is pointer-to-A.  Then call the instance method like you would any other.
There's no inheritance here, so some of the other examples wouldn't work.
Edit: Based on your username, I'm guessing you're more familiar with Java?  What you need is a Forward Declaration.  Basically this would be ChildClass.h:
class ParentClass; // Empty
class ChildClass
{
    ParentClass* myParent;
    // Body omitted
}

Ensure that ChildClass.h is included at the top of ParentClass.h and declare that normally, and include ParentClass.h in both .cpp files.  And ensure that all of the implementation of ChildClass is in the .cpp file, and the same for ParentClass (each in their own, or not, doesn't matter).
What's happening here is that you're creating a circular reference for the compiler, but in ChildClass.h all you need is to tell the compiler  "here's a pointer" and that's it.  Thus you don't need the "full size" of the class, thus the "empty" forward declaration is enough.  By the time the .cpp files roll around the compiler "knows" the full size of each, and doesn't throw errors.
See the C++ FAQ for more info on this.

A: If A::callMeWhenLongProcessFinished() is actually the only function you every want to call from B::longProcess(), you could just pass a pointer to your A object to the function:
void B::longProcess(A* object) {
    // long process
    object->callMeWhenLongProcessFinished();
}

If the setup isn't that trivial, you could instead have B::longProcess() take a std::function<void()> which is set up to call the proper function and call that instead:
void B::longProcess(std::function<void()> callback) {
    // long process
    if (callback) {
        callback();
    }
}

void some_function() {
    A* aptr = get_A_object();
    B* bptr = get_B_object();
    bptr->longProcess(std::bind(&A::callMeWhenLongProcessFinished, aptr));
}

Getting the calls being done in different threads will require sending the object around in a suitably thread-safe fashion but this is an entirely separate question.

A: Invoke the parent method at the end of your child method:
void ClassB::longProcess() {
  // do your processing
  // ...

  callMeWhenLongProcessHasFinished();
}

If, for some bizarre reason, you can't modify longProcess, write another method which calls the two methods serially.

A: You should Join on ClassB so that ClassA doesn't execute it's method until ClassB is finished.  Alternatively, just call the method from ClassA at the end of ClassB's method.


text:
Q: C# async methods still hang UI I have these two methods, that I want to run async to keep the UI responsive. However, it's still hanging the UI. Any suggestions?
async void DoScrape()
    {
        var feed = new Feed();

        var results = await feed.GetList();
        foreach (var itemObject in results)
        {
            var item = new ListViewItem(itemObject.Title);
            item.SubItems.Add(itemObject.Link);
            item.SubItems.Add(itemObject.Description);
            LstResults.Items.Add(item);
        }
    }

    public class Feed
    {
        async public Task<List<ItemObject>> GetList()
        {
            var client = new WebClient();
            string content = await client.DownloadStringTaskAsync(new Uri("anyUrl"));
            var lstItemObjects = new List<ItemObject>();
            var feed = new XmlDocument();
            feed.LoadXml(content);
            var nodes = feed.GetElementsByTagName("item");

            foreach (XmlNode node in nodes)
            {
                var tmpItemObject = new ItemObject();
                var title = node["title"];
                if (title != null) tmpItemObject.Title = title.InnerText;
                var link = node["link"];
                if (link != null) tmpItemObject.Link = link.InnerText;
                var description = node["description"];
                if (description != null) tmpItemObject.Description = description.InnerText;
                lstItemObjects.Add(tmpItemObject);
            }
            return lstItemObjects;
        }
    }

A: You seem to be confusing async with parallel.  They are both based on Tasks, but they are completely different.  Do not assume that async methods run in parallel -- they don't.
Async defaults to work in the same thread, unless there are reasons that force the async engine to spin up a new thread, such as the case when the main thread does not have a message pump.  But in general, I tend to think of the async keyword as running in the same thread.
You use WinForms, so the UI thread has a message pump.  Therefore, all your code above runs in the UI thread.
You must understand that you have NOT introduced any parallelism here.  What you have introduced via the async keyword is asynchronous operations, NOT parallel.  You have not done anything to "make your UI responsive" except for that one call to DownloadStringTaskAsync which won't force you to wait for the data to arrive, but you STILL have to do all the network processing (DNS lookup etc.) in the UI thread -- here is the asynchronous operation in play (you essentially "save" the time waiting for downloads).
In order to keep UI's responsive, you need to spin off time-consuming work into a separate thread while keeping the UI thread free.  You're not doing this with the async keyword.
You need to use Task.Factory.StartNew(...) to explicitly spin up a new thread to do your background processing.

A: How many items are you adding into your list view?
Unless you take action to prevent it, the WinForms list view will do a lot of processing every time you add an item into the list. This can take so long that adding just 100 items can take several seconds.
Try using BeginUpdate and EndUpdate around your loop to defer the bookkeeping of ListView until you're finished.
async void DoScrape()
{
    var feed = new Feed();

    var results = await feed.GetList();
    LstResults.BeginUpdate();  // Add this
    try
    {
        foreach (var itemObject in results)
        {
            var item = new ListViewItem(itemObject.Title);
            item.SubItems.Add(itemObject.Link);
            item.SubItems.Add(itemObject.Description);
            LstResults.Items.Add(item);
        }
    }
    finally
    {
        LstResults.EndUpdate();
    }
}

Got to use a try finally to avoid all sorts of pain if there's an exception.

A: I suspect DownloadStringTaskAsync relies upon HttpWebRequest.BeginGetResponse at a lower level. This being the case, it is known that the setup for a webrequest is not fully asynchronous. Annoyingly (and frankly, stupidly) the DNS lookup phase of an asynchronous WebRequest is performed synchronously, and therefore blocks. I suspect this might be the issue you are observing.
Reproduced below is a warning in the docs:

The BeginGetResponse method requires some synchronous setup tasks to complete (DNS resolution, proxy detection, and TCP socket connection, for example) before this method becomes asynchronous. As a result, this method should never be called on a user interface (UI) thread because it might take some time, typically several seconds. In some environments where the webproxy scripts are not configured properly, this can take 60 seconds or more. The default value for the downloadTime attribute on the  config file element is one minute which accounts for most of the potential time delay.

You've two choices:

*

*Start the request from a worker thread (and under high load, run the risk of ThreadPool starvation due to blocking behaviour)

*(Tenuously) Perform a programmatic DNS lookup prior to firing the request. This can be done asynchronously. Hopefully the request will then use the cached DNS lookup.

We went for the 3rd (and costly) option of implementing our own properly asynchronous HTTP library to get decent throughput, but it's probably a bit extreme in your case ;)


text:
Q: javascript "beforeunload" event not fire when i use update panel My problem is after I click a button in update panel and close the window,  "beforeunload" event not fire, while when I click another button this event fires properly.
Here is my code:
function dontlogout() //for postback refreshes
{
    postback = true;
    alert(postback);
}
$(window).bind('beforeunload',function() {

    if(postback==false)
    {
       //my logout code here;

    }

    else
    {
        postback = false;
     }
    });
<asp:Button runat="server" ID="cmdOut"  OnClientClick="dontlogout();" Text="next"  OnClick="cmdOut_Click"></asp:Button>

<asp:UpdatePanel runat="server" ID="updQuestion"   >
    <ContentTemplate>
<asp:Button runat="server" ID="cmdNext"  OnClientClick="dontlogout();"      Text="next" OnClick="cmdNext_Click"></asp:Button>

 </ContentTemplate></asp:UpdatePanel>

when i click cmdOut button no problem and when close browser my log out code executed, but when i click cmdNext in update panel and then close the browser my log out code not executed.
How can I solve this problem?

A: You have to return  in the function callback of onbeforeunload
$(window).bind('beforeunload',function() {

    if(postback==false)
    {
       //my logout code here;

      //  Ok you can leave because you dont return
    }

    else
    {
        postback = false;
        return  "You cannot leave";  // You cannot leave
     }
    });

A: Add the  'Triggers' tag just before the end tag of the update panel
<asp:UpdatePanel runat="server" ID="updQuestion"   >
    <ContentTemplate>
<asp:Button runat="server" ID="cmdNext"  OnClientClick="dontlogout();"      Text="next" OnClick="cmdNext_Click"></asp:Button>

 </ContentTemplate>
 <Triggers>
       <asp:PostBackTrigger ControlID="cmdNext" />
  </Triggers>
</asp:UpdatePanel>


text:
Q: Why is Atom behaving like this? whenever I hover over other items the appearance of atom worsens. A pic is attached here . Please help The Image
Not only the software atom, but Epic games also shows the same problem. The video of it is attached here
In addition to that, there is one more application thats behaving like this. I dont even know whats this problem actually called. Please help me solve this problem. Thank you.

A: It turned out the graphics drivers were not setup correctly. Now that I have reset the settings, everything works just fine and the white lines have disappeared from everywhere.


text:
Q: php DOMDocument()->getAttribute() not working I want to get the value of href attribute of a tag from HTML inside a string.
I have made a PHP fiddle here because the string is too long.
Error:
PHP Parse error:  syntax error, unexpected 'undefined' (T_STRING) in...

A: In php Sandbox your code works.
However, you forgot < at the beginning of a tag.
<?php
$string = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

             Show Name Detail

    ';

$doc = new DOMDocument();
$doc->loadHTML($string);
$selector = new DOMXPath($doc);
$result = $selector->query('//a[@title="Document Details"]');
$url = $result[0]->getAttribute('href');
echo $url;

In $url you have the href value (printed out).
It seems you have problem with the string and use of ' and ".
If you start the $string  with ' you cannot use it inside. You can use ' just at the end to close the php variable ';;
You have three solutions:

*

*substitute ' with " inside the string representing your html;

*Use \' instead of only ' inside the string representing your html. This tells to php that the string is not finished yet but that ' represents the string content;

*heredoc syntax;

For example with the first approach we have:
$string = ' Inside the string you should use just this type of apostrophe "    ';

A: For long multi-line strings, I prefer to switch to heredoc syntax which provide a more clean/visible way to handle strings and quotes within it. It also offers a "WYSIWYG display" of string as it is safe to insert line-breaks, tabs, spaces, quotes and double-quotes.
I switched your example to a HEREDOC syntax, and it run fine (with the correct result), except few warnings due to your malformed HTML input.
<?php

$string = <<<HTMLINPUT
Your multi-line HTML input goes here.
HTMLINPUT;

$doc = new DOMDocument();
$doc->loadHTML($string);
$selector = new DOMXPath($doc);
$result = $selector->query('//a[@title="Document Details"]');
echo $url = $result[0]->getAttribute('href');

Full example in a separate fiddle.
Hope it helps.


text:
Q: Checking input==null with @NonNull vs letting NPE be thrown public void test(@NonNull String input){
    #1 log(input.length());
}

*

*Using lombok @NotNull annotation removes boilerplate code. But if a null was passed as the input, it also ultimately throws an NPE (by default). So what's the difference in using @NonNull vs letting an NPE being thrown at line #1?

public void test(String input){
if(input ==null){
    throw NPE;
}
log(input.length());
}

*On a similar note, if the input is null and something could be done about it (e.x. set a default value or bypass the block if null), then it makes sense to do an explicit check for null. Otherwise is there any point in doing this check. Is it better to not do a null check and let NPE be thrown? If the answer to this question is, don't do null check, then why Lombok @NonNull exists?

A: "Fail fast" will help you in avoiding unwanted side effects. What if your method would dereference your null parameter after 20 lines, and within the 19 lines before, some state had already been changed (write to a log file, started transaction, some file or OutputStream creation)? In general, you don't want any of your method expressions to be executed if the API contract (parameter must not be null) has been violated.


text:
Q: Sum TimeSpan by extension method simplification I found here this extension method
/// <summary>
/// Calculates the sum of the given timeSpans.
/// </summary>
public static TimeSpan Sum(this IEnumerable<TimeSpan> timeSpans)
{
    TimeSpan sumTillNowTimeSpan = TimeSpan.Zero;

    foreach (TimeSpan timeSpan in timeSpans)
    {
        sumTillNowTimeSpan += timeSpan;
    }
    return sumTillNowTimeSpan;
}

usage:
List<TimeSpan> timeSpans = new List<TimeSpan>();
timeSpans.Add(TimeSpan.FromHours(1));
timeSpans.Add(TimeSpan.FromHours(2));
timeSpans.Add(TimeSpan.FromHours(3));
TimeSpan sum = timeSpans.Sum();// will be 06:00

Question:
Is this extension useful or could it be also be solved with one line linq like
TimeSpan sum = timeSpans.Sum(); //Linq.Sum() - this doesn't compile

I would expect this to compile since Sum() does internal += all values - the curious about his is that intellisense of Visual Studio suggests me to use Sum() and there is a existing overload but it doesn't compile.

A: Since Linq's Sum is not available for IEnumerable<TimeSpan>, another alternative is to use Aggregate instead.
TimeSpan sum = timespans.Aggregate(TimeSpan.Zero, (t1,t2) => t1.Add(t2));

A: So the following doesn't compile...
List<TimeSpan> timeSpans = new List<TimeSpan>();
timeSpans.Add(TimeSpan.FromHours(1));
timeSpans.Add(TimeSpan.FromHours(2));
timeSpans.Add(TimeSpan.FromHours(3));
TimeSpan sum = timeSpans.Sum();// will be 06:00

An alternative to the extension method supplied would be ...
TimeSpan sum = TimeSpan.FromMilliseconds(timeSpans.Sum(t => t.TotalMilliseconds));

EDIT: As pointed out by TheGeneral better to use the Ticks long property to avoid rounding errors if nanoseconds are a concern...
TimeSpan sum = TimeSpan.FromTicks(timeSpans.Sum(t => t.Ticks));

Although I think I actually prefer kurakura88's answer as it uses TimeSpan's Add method which should be more reliable than any other method you could use to Add TimeSpans

A: I like Mick's answer, though I'd use ticks so you don't lose precision.
If you have Printable Character OCD you can put it in your own awesome extension:
public static class TimeSpanExtensions
{
   public static TimeSpan Sum(this IEnumerable<TimeSpan> source)
      => TimeSpan.FromTicks(source.Sum(t => t.Ticks));
}

Usage
List<TimeSpan> timeSpans = new List<TimeSpan>();
timeSpans.Add(TimeSpan.FromHours(1));
timeSpans.Add(TimeSpan.FromHours(2));
timeSpans.Add(TimeSpan.FromHours(3));
TimeSpan sum = timeSpans.Sum();


text:
Q: php loop array assignment I have an array that looks like the one below. I would like to iterate over a loop and assign to 3 different variables the corresponding strings. so for instance:
Output:
$mike = 'foo - ';
$john = 'bar foo foo - bar foo foo - bar foo bar - '
$bob =  'bar foo bar bar foo - bar foo - '

What would be a short(est) way of doing this? thanks
Initial array
Array
(
    [mike] => Array
        (
            [0] => foo -
        )
    [john] => Array
        (
            [0] => bar foo foo -
            [1] => bar foo foo -
            [2] => bar foo bar -
        )
    [bob] => Array
        (
            [0] => bar foo bar -
            [1] => bar foo -
            [2] => bar foo -
        )
)

A: This is a case for variables variables:
foreach ($array as $key => $values) {
   $$key = implode($values);
}

However, you may not really need them. I would use an array instead:
$result = array();
foreach ($array as $key => $values) {
   $result[$key] = implode($values);
}

So you'd get:
Array
(
    [mike] => foo -
    [john] => bar foo foo - bar foo foo - bar foo bar -
    [bob] => bar foo bar - bar foo - bar foo -
)

A: use extract() and implode()
$a = array( 'mike'  => array('foo -'),
            'john'  => array('bar foo foo - ',
                             'bar foo foo - ',
                             'bar foo bar - '
                            ),
            'bob'   => array('bar foo bar - ',
                             'bar foo - ',
                             'bar foo - '
                            )
          );

foreach($a as $k => $v) {
    $a[$k] = implode(' ',$v);
}
extract($a);

var_dump($mike);
var_dump($john);
var_dump($bob);


text:
Q: Get html source code from a website and then get an element from the html file I want to get HTML code of a website and then get a certain element from that HTML file.
There are things that can get HTML code like ajax and jquery. I am using node and want it to be in total javascript. Also, I have no idea how to get a certain element from that.
I have done this in python but I need it in javascript. For simplicity. Let's take the website- https://example.com. This is the body of the HTML code of website.

    #Some Stuff

I want to get the div class lets take
 to be
 to make it easier.
Finally, I want to get- the content of

Like this-

    #Some Stuff

Thanks in Advance

A: For Node.js there are two native fetching modules: http and https. If you're looking to scrape with a Node.js application, then you should probably use https, get the page's html, parse it with an html parser, I'd recommend cheerio. Here's an example:
// native Node.js module
const https = require('https')
// don't forget to `npm install cheerio` to get the parser!
const cheerio = require('cheerio')

// custom fetch for Node.js
const fetch = (method, url, payload=undefined) => new Promise((resolve, reject) => {
    https.get(
        url,
        res => {
            const dataBuffers = []
            res.on('data', data => dataBuffers.push(data.toString('utf8')))
            res.on('end', () => resolve(dataBuffers.join('')))
        }
    ).on('error', reject)
})

const scrapeHtml = url => new Promise((resolve, reject) =>{
  fetch('GET', url)
  .then(html => {
    const cheerioPage = cheerio.load(html)
    // cheerioPage is now a loaded html parser with a similar interface to jQuery
    // FOR EXAMPLE, to find a table with the id productData, you would do this:
    const productTable = cheerioPage('table .productData')

    // then you would need to reload the element into cheerio again to
    // perform more jQuery like searches on it:
    const cheerioProductTable = cheerio.load(productTable)
    const productRows = cheerioProductTable('tr')

    // now we have a reference to every row in the table, the object
    // returned from a cheerio search is array-like, but native JS functions
    // such as .map don't work on it, so we need to do a manually calibrated loop:
    let i = 0
    let cheerioProdRow, prodRowText
    const productsTextData = []
    while(i < productRows.length) {
      cheerioProdRow = cheerio.load(productRows[i])
      prodRowText = cheerioProdRow.text().trim()
      productsTextData.push(prodRowText)
      i++
    }
    resolve(productsTextData)
  })
  .catch(reject)
})

scrapeHtml(/*URL TO SCRAPE HERE*/)
.then(data => {
  // expect the data returned to be an array of text from each
  // row in the table from the html we loaded. Now we can do whatever
  // else you want with the scraped data.
  console.log('data: ', data)
})
.catch(err => console.log('err: ', err)

Happy scraping!

A: See the working example below. You can do more stuff in the for loop if necessary.
In general you can access the Html-Content of most Objects via .innerHTML.

var divs = document.getElementsByClassName("test");
for(var i = 0; i < divs.length; i++)
{
   console.log(divs[i].innerHTML);
}

    #Some Stuff

When you want to get the SourceCode of a Site on the same Domain you can use this How do I get source code from a webpage? and combine it with my given solution for your second problem.

A: You will never be able to get the source code of a page that is not on the same domain as your page in javascript.
Please take a look :
http://en.wikipedia.org/wiki/Same_origin_policy
If the domain is the same you can get it by iFrames:
var url=".../xxxx"; // same domain !
var iframe=document.createElement("iframe");
iframe.onload=function()
{
var result= iframe.contentWindow.document.body.querySelector('.test').innerHTML);
alert(result);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);

var result access the iframe and select the element that have class named "test" and get its inner html in your case the result will be :
    #Some Stuff


text:
Q: How to write a jasmine unit test case to test the event handlers in angularjs I am currently writing a jasmine unit test case to test the button's click event. I have written the following test cases for modal popup, please find my plnkr here. I have a button called Add. If the user clicks the button a modal popup opens. So I want to write a test case to find whether the modal is displayed when the user clicks the add button. How do I do it?
Thanks,
Varun Krishna. P

A: First of, as with all unit tests, make sure that you're not mixing N tests into one - that always causes trouble.
In your case, the test can be split into 2 tests:

*

*Is the correct function called when Add is clicked?

*Does the function display a model dialog?

For the first test, I suggest that you move the code for the event handler into a function instead of in-lining it. That way, you can overwrite the function in the test setup and restore it later (pseudo-code):
// setup
var origFunc = addFunction;
var iWasCalled = false;
addFunction = function() { iWasCalled = true; }

// test
$('#add').click();

// validation
assert that iWasCalled is now true

// tear down
addFunction = origFunc

The second test means now that you call the new function and check whether there now a modal popup in the DOM.


text:
Q: How to map function keys in less? Is it possible to map function keys (F1-F12) in less with lesskey?
This doesn't seem to work:
#command
F1    forw-line

A: Historically, terminals use escaped sequences for functions keys, cursor keys and more. The termcap and terminfo facilities help to deal with the variations across terminals.
First you need  to determine what your terminal sends when you hit F1, in bash you can do:
printf "%q\n" "CtrlV F1"
Within the second pair of quotes you type Ctrl+V to cause the next keystroke to be treated literally (verbatim), and then F1.
On my terminal (rxvt) I see
$'\E[11~'

so my F1 sequence is escape [ 11 ~, so into .lesskey should go
#command
\e[11~  forw-line

run lesskey to update, and now F1 will invoke that command.
infocmp is another way to see how your terminal is set up, e.g.
infocmp -L1 rxvt | grep key_f1=

See Stéphane Chazelas answer here for more details on that, though less doesn't use readline, configuring readline requires a similar understanding.


text:
Q: 2D collision detection of images with transparent parts ignored So I decided to look up some collision detection but I've been having trouble finding proper information
regarding 2d collision detection between two images that includes how to properly avoid detecting the transparent
areas of an image but I did find one post which I got myself attached to but the problem is that I don't
really understand the post nor do I understand why he does some of those things...
Here's the post in question: https://stackoverflow.com/posts/336615/revisions
So first of all I want to ask if this solution is actually a good one / proper or if I should just look elsewhere.
Secondly I wonder, in his post, he mentions using integer arrays, not 2d arrays either it seems,  to
set 1 and 0 to decide  whether or not the pixel is transparent or not but I don't really know how I am supposed
to achieve this. At first I thought it could be achieved by just forming a string of 1 and 0s and convert it to a Long
but even with a mere image width of 25, the Long, gets... too long...
I also tried this with no luck, since the code does not function with this array:
 long[] array = new long[30*30]; // height * width of the image
    int x = 0;
    int y = 0;

for(int i = 0; i<30*30; i++){
    if(image.getRGB(x,y) == 0){
         array[i] = 0;
    }
    else{ array[i] = 1; }

    x++;
    if (x==30){
         y++;
         x=0;
    }
}

Thirdly, I was hoping someone could maybe explain the whole process and why the things he does, are necessary.
By the way, I do know how those bit wise operators work!
In other words, I don't understand his train of thought / motivation for doing the all things in the code and I would like to gain an understanding of all this!
I don't really know how to proceed right now hehe...

A: The result of the bitwise AND operation (&) is true (1) for each each bit where the the corresponding bit is true in both operands, and false (0) otherwise.
The idea he's using is to create a version of the image (a mask) where each non-transparent pixel in the original image is stored as a '1' bit, and each transparent pixel as a '0' bit. These are packed into a single integer, which can be tested against the mask for another image with a single AND operation (before the AND he calculates the horizontal distance between the two images and shifts one of the masks if necessary).
For example, let's assume that we have the following two 4x1 pixel images:
5, 0, 0, 5
      8, 8, 8, 8

Although I placed them on separate rows here for practical purposes, you should view them as being on the same row, so the last two pixels of the left image overlap with the first two of the right image.
The masks for the rows when viewed in binary representation would be:
1001
1111

The distance between the left and right image is -2, so we shift the first mask left by 2 bits:
1001 << 2 => 100100

So now we have these masks:
100100
001111

ANDing these gives us:
000100

The non-zero result tells us that we have a collision.


text:
Q: Run only method from .py file using crontab There is .py file with multipe methods in it.
I want to run a specific method from that file every 15 minutes.
I can edit crontab on server and something like following :
*/15 * * * * /usr/bin/python /path/to/my/file.py

But this will run entire python file. How do I run only method of that file ?

A: Assuming, it a class / instance method, I would do something like below :
*/15 * * * * /usr/bin/python /path/to/my/file.py <<some_param>>

now in file.py
class A(object):
   def foo1(self):
     pass
   def foo2(self):
     pass

if __name__ == "__main__":
   if len(sys.argv > 1):
      option = sys.argv[1]
      if option == <<some_param>>:
         obj = A()
         obj.foo1()

If its simple @staticmethod, @Burhan's comment would work fine! :)

A: I have one file with 2 function file1.py
def something():
    print ('something')
def somethingElse():
    print ('something else')

another file file2.py
import file1
file1.something()

you can setup cron on the file2.py


text:
Q: Vue Jest - Div element still exists when v-if is false I have a small project where I am learning to write jest Unit tests in Vue. Inside this project I have a HiChild component which gets a message props. When the length of this message is smaller then 3 then a error div should show. I use v-if="error" to check if the I should show the div or not.
This is the component:
<template>

The child says {{ message }}

{{ error }}

</template>

But in the unit test I wrote for this component I have a test where I test if the div actually
exists when the error variable is not empty and not exist when it is empty. But the test does not pass when it should be empty.
This is the unit test I wrote:
describe('HiChild.vue', () => {
  it('renders error when message is too short', () => {
    const wrapper = shallowMount(HiChild, {
      propsData: { message: 'hi' },
    });
    expect(wrapper.find('.error').exists()).toBe(true);

    wrapper.setProps({ message: 'good day to you!' });
    expect(wrapper.find('.error').exists()).toBe(false);
  });
});

And here is the output from the test:

A: Because :
 computed: {
    error() {
      return this.message.trim().length < 3
        ? " The child can say bigger words than that!"
        : "";
    },

"" is different to false
"" !== false

return directly false like that
 computed: {
    error() {
      return this.message.trim().length < 3
        ? " The child can say bigger words than that!"
        : false;
    },

Regards


text:
Q: applying jasny input mask on knockout load I am attempting to apply the jasny bootstrap input mask to a text input that is databound using knockout.  however the datamask does not show up until you click on the input box. I'm not sure why.  I would like the input mask to show up right away.  here is the fiddle.  http://jsfiddle.net/LkqTU/31938/
here is the html

        First Name
        Last Name
        Phone

          <input type="text" class="form-control" data-bind="value: phone" data-mask="999-999-9999">

and here is the javascript.
function employee(firstName, lastName, phone) {
  this.firstName = ko.observable(firstName);
  this.lastName = ko.observable(lastName);
  this.phone = ko.observable(phone);

}

function model() {
  var self = this;
  this.employees = ko.observableArray("");
}

var mymodel = new model();

$(document).ready(function() {
  loaddata();
  ko.applyBindings(mymodel);
});

function loaddata() {
  mymodel.employees.push(new employee("Bob", "Jones", "7174569876"));
  mymodel.employees.push(new employee("Mary", "Smith", "3457892435"));
  mymodel.employees.push(new employee("Greg", "Black", "3557689800"));
}

A: Try initializing the input mask on document load, after your Knockout bindings have been applied:
$(document).ready(function () {
    loaddata();
    ko.applyBindings(mymodel);
    $('.form-control').inputmask({
      mask: '999-999-9999'
    })
});

Be sure to remove your data-mask attribute as well.
JS Fiddle example


text:
Q: Software upgrade solution in Solaris I am working on developing an software.
I have installed the v1.0 on my machine running solaris 10,
and I want to upgrade to version 1.1 tha has some new function.
I do not want to uninstall version 1.0 but upgrade to version 1.1.
How do I make a patch?
Writing a script or using some patch tools?

A: If you are asking about Solaris patches, i.e. those appling to SVR4 packages, I guess only Solaris engineering is able to build and deliver them as there is no standard/documented format I'm aware of. The new version of Solaris (11) is going to abandon this patching method anyway to the new pkg mechanism.
If you want a new version not to replace the older one, I guess the simplest way would be to have them to install in different directories. eg: /opt/zhangli/v1.0 and /opt/zhangli/v1.1. Any packaging format would support that.