text:
Q: $||u||_2= \sup_{x \in K} |u(x)|$ is not a norm when $K$ is closed subset of $\mathbb R^k$ and $u(x)$ is a continuous function on $K$. $K \subset \mathbb R^n$  and  $K$ is closed.  $C(K)$  is the set of all continuous function form $K$  to $\mathbb R$.
Now for every $u(x) \in C(K)$   , $||u||_2= \sup_{x \in K} |u(x)|$.
$||u||_2$ is not a norm function as $||u||_2$ will not be defined for many elements of $C(K)$.
E.g. $[0 , \infty)$  is a closed subset of $\mathbb R$.
Now the function $f(x) = x^2$  is a continuous function on $\mathbb R$ and unbounded above.
Have I gone wrong anywhere ? Can anyone please check my solution ?

A: Your solution seems perfectly OK. You correctly identified the problem, which is that the supremum value is not defined for all elements of $C(K)$.
The only minor correction (which is more or less semantic) I would make is to say that the function $f(x)=x^2$ is a continuous function on $[0, \infty)$. Sure, it is also continuous on $\mathbb R$, but in your case, you want to show that it is an element of $C(K)$, and $K$, in this case, is $[0,\infty)$.
Note that if $K$ were a compact, and not just a closed, set, then your counterexample would no longer work. Nor would any other, because if $K$ is compact, then the defined mapping is a norm on $C(K)$.


text:
Q: Pair Rotation in a team for effective pair programming We follow pair programming in our company and always face the issue of balanced and effective pair rotation within the developers on stories.
We follow a simple metrics in which every developer's name is mapped with every other developer and we mark the respective intersection whenever two developers are pairing.
This is not working out well, we cannot track how much time a pair has spent pairing and people forget to update the metrics many times. Tracking the pair rotation is helpful because we want the project knowledge to be shared across the team, and not just one pair. So usually what happens is, whoever is pairing keeps pairing till the entire story is completed (given they have better context), and no body else knows about what is being done & if the story or a regression/production bug comes back, the same pair has to pick it up (leaving whatever they are currently doing), which is what creates a bottleneck.
Are there any known metrics that can be used for tracking the pair rotations.

A: Why do you feel the need to track the amount of time developers have paired with each other?  Is it because you want to remove the bottlenecks that you mentioned or want to share knowledge around the team, or because the code you're releasing to production is buggy?
I'd suggest tracking the things that are important to you and leave it up to the team to workout how best to achieve them.
As an example, track whenever a story has to be assigned to a specific pair and try and bring that number to zero over time.

A: I'm not sure that you want to do this. Your reason for pairing is very good - sharing knowledge across the team, making sure that multiple people are exposed to different parts of the code so you have more people to be able to work in areas. However, the whole idea of timeboxing pairs, especially in the middle of a particular work item (a story, a bug, whatever) doesn't seem like a good idea.
Breaking up a pair in the middle of a story interrupts flow. You have two people who have come together and are working effectively to solve a problem. In the middle of them coming up with a solution, implementing, and testing it, you rip them apart and try to create a new pair. This new pair needs to develop as a team, get on the same page, and then continue with the work - the net result is a disruption to productivity and quality.
I like the idea of creating new pairs, but only when it makes sense. I would advocate pairs working together for a sprint. In order to better spread pairs around, do keep track of who has paired and try to keep new people working together. Of course, if there are people who don't work well together, you may want to avoid that pairing in the future.
Your concerns about needing to interrupt work if there is a regression, a bug, or the story comes back up doesn't make sense to me. That approach of "drop everything to fix an issue" isn't agile. Unless the issue is a showstopping issue, it should be put into the backlog and prioritized and fixed when appropriate. If it is urgent and needs to be immediately addressed, you don't need the same pair to work on it. Assign it to a pair that has someone who has knowledge of that part of the code. This leaves you with one person who understands the functionality along with the design and implementation and someone who can now learn it as they implement the fix.

A: One thing I would consider is the size of your stories. Can you break them down into smaller chunks, so that it is easier for new pair combinations to pick up? Are you frequently running into a single story taking a sprint or more worth of work? Can you scope a story down to one to two days, making larger more complex features into smaller vertical slices of value that can be delivered sooner?
If a story takes a week or more to complete, then I can absolutely see where it would be difficult for engineers to want to rotate pairs. Engineers typically want to see something to fruition. By structuring your stories, where possible, into smaller vertical slices of value that can be delivered quickly, your allowing for more opportunities for a pair to complete a portion of work to the end, reducing friction to the idea of 'rotating off before delivering value'.
This approach also helps engineers get into the mindset of constant delivery of value, where small check-ins are the norm, versus large feature releases.

A: Assign a pair anchor that will be on the task from start to the end. A task estimation should not be longer then 2/3 days.
Switch pair every half a day. Thomas description of breaking flow would be correct if there was no anchor left.
If you want a visual feedback keep a pairing table on your whiteboard and let the anchor update who he paired with.
Beware not everybody is happy to switch that often, some people prefer to see a feature from the start to the end often with the same person. I think this creates knowledge silos and requires for long code review processes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find the lowest value of a set of records in column A based on particular values in Column B? I have two columns in a data frame containing more than 1000 rows. Column A can take values X,Y,None. Column B contains random numbers from 50 to 100.
Every time there is a non 'None' occurrence in Column A, it is considered as occurrence4. so, previous non None occurrence in Column A will be occurrence3, and the previous to that will be occurrence2 and the previous to that will be occurrence1. I want to find the minimum value of column B between occurrence4 and occurrence3 and check if it is greater than the minimum value of column B between occurrence2 and occurrence1. The results can be stored in a new column in the data frame as "YES" or "NO".
Sample Input

For example, I need to find the minimum value of Column B between ROWNUM 14 and ROWNUM 11 and compare it with the minimum value of Column B between ROWNUM 6 and ROWNUM 3. Next I need to compare the minimum value between ROWNUM 22 AND ROWNUM 14 and compare it with the minimum value between ROWNUM 11 and ROWNNUM 6.
UPDATE:
import numpy as np
import pandas as pd

df = pd.DataFrame([[0, 0]]*100, columns=list('AB'), index=range(1, 101))
df.loc[[3, 6, 11, 14, 22, 26, 38, 51, 64, 69, 78, 90, 98], 'A'] = 1
df['B'] = np.random.randint(50, 100, size=len(df))
df['result'] = df.loc[df['A'] != 0, 'B'].rolling(4).apply(
    lambda x: x[-2:].min() > x[:2].min(), raw=True)
print(df)
df.to_excel("rollingwindow.xlsx",sheet_name="example")

a_guest, I used your code and the output is as follows.

The minimum value between row 22 and row 14 is 56 which is greater than the minimum value between row 11 and 6 which is 54. So, result must be 1 but your code generates 0.

A: You can use a sliding window to perform the comparison:
result = df.loc[df['A'] != 0, 'B'].rolling(4).apply(
    lambda x: x[-2:].min() > x[:2].min(), raw=True)

If the non-zero items should not be compared directly but instead their locations should serve as boundaries for the particular ranges then you can use this modification:
result = df.index[df['A'] != 0].to_series().rolling(4).apply(
    lambda x: df.loc[x[2]:x[3], 'B'].min() > df.loc[x[0]:x[1], 'B'].min(), raw=True)

For reference, here's the example data frame (using 0 for None and 1 otherwise, but the principle is the same):
import numpy as np
import pandas as pd

df = pd.DataFrame([[0, 0]]*24, columns=list('AB'), index=range(1, 25))
df.loc[[3, 6, 11, 14, 22], 'A'] = 1
df['B'] = np.random.randint(0, 100, size=len(df))
print(df)

Which looks as follows:
    A   B
1   0  98
2   0  99
3   1  73
4   0  42
5   0  76
6   1  80
7   0  91
8   0  40
9   0  15
10  0  51
11  1  93
12  0  82
13  0  73
14  1  86
15  0  71
16  0  84
17  0  62
18  0  20
19  0  53
20  0  12
21  0  68
22  1  97
23  0  74
24  0  51


text:
Q: Multidimension array versus nested lists in python Aside from the different accessing methods (e.g. [1,2] instead of [1][2] to access element in 2nd row and 3rd column), what are the differences between multidimensional arrays and nested lists in python? Why are both data structures necessary?

A: Python does not have a multidimensional array type. It only has lists.
numpy (a 3rd-party Python extension) does have array types, and these serve a specialized function within that library, namely fast C-based mathematical operations on homogenous sequences.
With the standard Python list type, putting one inside the other creates a nested structure that can be used to model a multidimensional structure. You nest the [index] item access, [1][42] first retrieves the second element of the outer list, then the 43rd element of that second element.
numpy arrays are specialist structures that explicitly model multiple dimensions as part of the main type, rather than nesting arrays inside arrays, and that means they can support addressing of multiple dimensions in the [index] syntax, where index comes in the form of a tuple, technically.
Python does have a single dimensional array type, that, like numpy arrays, models homogenous C-type sequences.


text:
Q: Write External Storage on Android 4.4 and above I am trying to write the external storage but I always get the Access denied message.
I set the correct permissions on the manbifest and also I request the write_external_storage permissions at runtime and I am able to write the primary external sdcard:
in my case
/sdcard (/storage/emulated/0/)
but I cannot write on the secondary external SD (microsd card) :
in my case
/storage/C0B9-3B8B/
I can write the secondary memory only using the path
/storage/C0B9-3B8B/Android/data/com.example.myapplication/files/
Is there any way to write a different folder, for example
"/storage/C0B9-3B8B/Download" without rooting the device?
Thank you

A: I found a solution for my issue, I need to use the SAF (Storage access framework) as Google describes HERE


text:
Q: how can i use an array of values inside where clause in knex? How can i use an array of value to compare inside the where clause like in the below code, 'frompersons' is an array of names coming in response from the first call and I want to get out their info from 'chatterusers' database. But how can i use this array inside the next  where clause ?
return knex('frndrqst').where({ toperson: toperson })
            .select('fromperson')
            .then(frompersons => {

                  db.select('*').from('chatterusers')
                    .where( 'name', '=', frompersons )
                    .then(data => {
                        res.json(data);
                    })
                    .catch(err => res.json("Unable to load frndrqsts !!!"))
                })
            .catch(err => res.json("Unable to load frndrqsts !!!"))

A: //get the list of name from 'formperson' table

var subquery = knex.select('name').from('fromperson');

//get in all information from 'chatterusers table' that name is equal with name

return knex.select('*').from('chatterusers')
  .whereIn('name', subquery)

output :
select * from chatterusers where name in (select name from fromperson)


text:
Q: Fix already commited CRLF in git I have set git to core.autocrlf = true. However it seems there are already commited files that have CRLF inside the repository. When I modify such a file, then git seems to assume that no implicit conversion is necessary and as a result git diff shows those annoying ^M at the end of each line. For other files which are checked out as CRLF but commited as LF I do not see any ^M at the end of changed lines. How can I fix the problematic files in my repository?
I do not want to use solutions that use git filter-branch since I do not want to rewrite the history. I want to create add a new commit that fixes the problematic files. Preferably I would like to fix individual files and not everything at once.

A: Use your favorite text editor to change all CRLF to LF. Any good programming editor or IDE has an option for which EOL sequence to use. Change it to Unix style and reformat all files in your project. Then make a commit.


text:
Q: How do I select a piece of text with regex and then use findall? I have the following code. How I select the name2 and name3 from the "suite-title">author
 field with regex?

thinker

                                        name1

author

                                        name2

                                        name3

I could write the following code that just gives me the name2:
    re.findall( r'
author
\s+
\s+
\s+(.*?)'
, string = content.text)

A: You could find a way to do this with a global regex, but it is probably better to split the html into a list of lines and process each line, setting a flag when you are in the right place and using re to capture the names.
in_author = False
authors = []
for line in html.split('\n'):
    if line.count('<h3'):
        if line.count('author
'):
            in_author = True
        else:
            in_author = False
    if in_author and line.count('<a'):
        match = re.match(r' *(.*)', line)
        if bool(match):
            authors.append(match.group(1))
print(authors)

As mentioned in the comments, using an HTML parser is probably a better way to go:
from bs4 import BeautifulSoup
authors = []
soup = BeautifulSoup(html, 'html.parser')
for link in soup.find_all('a'):
    if link.find_previous('h3').string == 'author':
        authors.append(link.string)
print(authors)

While using any html parsing tool comes with a bit of a learning curve, it is well worth the effort if you plan on doing more structured markup text processing in the future.


text:
Q: Computing 3D coordinates of keypoints in multiple images I have multiple images of an object taken by the same calibrated camera. Let's say calibrated means both intrinsic and extrinsic parameters (I can put a checkerboard next to the object, so all parameters can be retrieved). On these images I can find matching keypoints using SIFT or SURF, and some matching algorithm, this is basic OpenCV. But how do I do the 3D reconstruction of these points from multiple images? This is not a classic stereo arrangement, so there are more than 2 images with the same object points on them, and I want to use as many as possible for increased accuracy.
Are there any built-in OpenCV functions that do this?
(Note that this is done off-line, the solution does not need to be fast, but robust)

A: I guess you are looking for so-called Structur from motion approaches. They are using multiple images from different viewpoints and return a 3D reconstruction (e.g. a pointcloud). It looks like OpenCV has a SfM module in the contrib package, but I have no experiences with it.
However, I used to work with bundler. It was quite uncomplicated and returns the entire information (camera calibration and point positions) as text file and you can view the point cloud with Meshlab. Please note that it uses SIFT keypoints and descriptors for correspondence establishment.

A: I think I have found a solution for this. Structure from motion algorithms deal with the case where the cameras are not calibrated, but in this case all intrinsic and extrinsic parameters are known.
The problem degrades into a linear least squares problem:
We have to compute the coordinates for a single object point:
X = [x, y, z, 1]'
C = [x, y, z]'
X = [[C], [1]]

We are given n images, which have these transformation matrices:
Pi = Ki * [Ri|ti]

These matrices are already known. The object point is projected on the images at
U = [ui, vi]

We can write in homogeneous coordinates (the operator * represents both matrix multiplication, dot product and scalar multiplication):
[ui * wi, vi * wi, wi]' = Pi * X

Pi = [[p11i, p12i, p13i, p14i],
      [p21i, p22i, p23i, p24i],
      [p31i, p32i, p33i, p34i]]

Let's define the following:
p1i = [p11i, p12i, p13i] (the first row of Pi missing the last element)
p2i = [p21i, p22i, p23i] (the second row of Pi missing the last element)
p3i = [p31i, p32i, p33i] (the third row of Pi missing the last element)

a1i = p14i
a2i = p24i
a3i = p34i

Then we can write:
Q = [x, y, z]
wi = p3i * Q + a3i
ui = (p1i * Q + a1i) / wi =
   = (p1i * Q + a1i) / (p3i * Q + a3i)
ui * p3i * Q + ui * a3i - p1i * Q - a1i = 0
(ui * p3i - p1i) * Q = a1i - a3i

Similarly for vi:
(vi * p3i - p2i) * Q = a2i - a3i

And this holds for i = 1..n. We can write this in matrix form:
G * Q = b

G = [[u1 * p31 - p11],
     [v1 * p31 - p21],
     [u2 * p32 - p12],
     [v2 * p32 - p22],
     ...
     [un * p3n - p1n],
     [vn * p3n - p2n]]

b = [[a11 - a31 * u1],
     [a21 - a31 * v1],
     [a12 - a32 * u2],
     [a22 - a32 * v2],
     ...
     [a1n - a3n * un],
     [a2n - a3n * vn]]

Since G and b are known from the Pi matrices, and the image points [ui, vi], we can compute the pseudoinverse of G (call it G_), and compute:
Q = G_ * b


text:
Q: Detailed stack trace: Error: Cannot find module 'stripe' I am working with stripe payment in flutter application. Flow is I am generating a token  of card and send to fire base later cloud function will get card detail and use stripe API to charge the payment I am facing a problem npm install strip successfully install the stripe but when I run the firebase deploy it shows the error.
here is I am writing cloud function.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//const firestore= admin.firestore();
//const setting ={timestampInSnapshots:true};
// firebase.setting(setting);
const stripe = require('stripe')(functions.config().stripe.testkey)
exports.addStripeSource =functions.firestore.document('cards/{userid}/Tokens/{tokenid}}')
.onCreate(async (tokenSnap, context)=> {
   var customer;
   const data=tokenSnap.aftter.data();
   if(data == null){
       return null;
   }
   const token =data.tokenId;
   const snapshot =await firestore.collection('cards').doc(context.params.userId).get();
   const customerId=snapshot.data().custId;
   const customerEmail=snapshot.data().Email;
   if(customerId == 'new')
   {
       customer= await stripe.customers.create({
           email: customerEmail,
           source: token,
       });
       firestore.collection('cards').doc(context.params.userId).update  ({
           custId: customer.id,
       })
   }
   else{
       customer= await stripe.customers.retrieve(customerId);
   }
   const customerSource= customer.sources.data[0];
   return firestore.collection('cards').doc(context.params.userId).collection('sources').doc(customerSource.card.fingerprint).set(customerSource)

}
)

package.json file
{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "8"
  },
  "dependencies": {
    "firebase-admin": "^8.6.0",
    "firebase-functions": "^3.3.0"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.1.6"
  },
  "private": true

}

A: I had the same problem. found out I needed to open terminal or command prompt and cd to the 'functions' folder for firebase and then run npm install stripe there. Once that was done, it worked.

A: Make sure you installed the package from the functions directory instead of the project directory. I accidentally installed packages while in the project directory, It works locally fine, but creates error when you deploy it. so,
cd functions
npm install [your package]

Then it will work fine

A: It seems you installed strip instead you should install the following:
npm install stripe --save

https://www.npmjs.com/package/stripe

A: steps:
this also worked for me i had done the install in the right folder as in firebase functions folder (backend), and was having problems when i tried to deploy it using:
firebase deploy --only functions Command, when the issue arose  i ran the firebase functions log command firebase function log: --only "Myfunction name here".
in the logs i found the error that: Detailed stack trace: Error: Cannot find module 'stripe' so i installed stripe using:
npm install @stripe/stripe.js....this did not fix the problem! i had to install stripe like this first: npm install stripe and after this i ran the previous command: npm install @stripe/stripe.js
after this i ran the firebase deploy command: firebase deploy --only functions and voila! everything works - deployment complete! - hope this helps someone!


text:
Q: Error: Invalid Adapter :idb in pouchdb + ionic 3 with using chrome (Version 63.0) I am using pouchDb +ionic 3. During creating pouchDb with ionic 3 without mention any parameter (by default: websql) it's working fine. But whenever I try to use adapter (indexedDB) like :
setupDB() {
 this.db = new PouchDB('Contacts', {adapter : 'idb'});
 }

it's thrown an error :
ERROR Error: Invalid Adapter: idb
at new PouchDB$5 (VM46 vendor.js:118540)

Please Help.

A: I think this is a known issue specifically for iOS mobile.
You can see this being discussed in this thread:
https://github.com/pouchdb/pouchdb/issues/6946
Seems like the fix is in flight:
https://github.com/pouchdb/pouchdb/issues/7085
So we should upgrade soon and this will hopefully resolve it.
UPDATE: ALSO make sure your iOS browser is NOT in incognito mode. Such modes do not allow persistence of data.


text:
Q: Mongoose count skip limit I am implementing pagination.
What I am doing is counting the items from collection first & after that count will return. I am then doing another find with skip and limit.
Now I want to assign count to the data returned by 2nd query which I am not able to do.
I tried toObject() but I am getting error "toObject() is not a function".
I don't want to use any library.
ErrorReportModel.find().count(function(err, count) {
  if (err) {
    console.log(err);
    utile.internalError(res);
  }
  ErrorReportModel.find().sort({
    date_create: -1
  }).limit(20).skip(query.page * 20).lean().exec(function(err, data) {
    if (err) {
      console.log(err);
      utile.internalError(res);
    }

    // i am doing this at the moment
    var myData = {};
    myData.data=data;

    myData.count = count;

    utile.response(res, myData);
  });
});

I want to send the count to client side because I want to display page_number buttons depending on that count.


text:
Q: How to support bangla font in a webview while developing Android software I am trying to load a html file in a webView that contains Bangla sentences.But I'm having trouble to do this.Web page is showing, But the fonts or the sentences are not showing.
My code is here...
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.physics_1st_chap1);

    WebView myWebView = (WebView) findViewById(R.id.webviewc1);
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.setWebChromeClient(new WebChromeClient());
    myWebView.loadUrl("file:///android_asset/mathscribe/vector.html");

}

A: asset/demo.html
<html>
<head>
    <meta http-equiv="content-type" content="text/html;" charset="UTF-8">
        <style>
            /** Specify a font named "MyFont",
            and specify the URL where it can be found: */
            @font-face {
                font-family: "MyFont";
                 <!-- you can set Custom font here -->
                src: url('file:///android_asset/fonts/BLKCHCRY.TTF');
            }
            h3 { font-family:"MyFont"}
        </style>
</head>
<body>
    <h3>
        Welcome to CustomFont Demo
    </h3>
</body>

public class MainActivity extends Activity {

WebView mWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Getting reference to WebView of the activity_main layout
    mWebView = (WebView) findViewById(R.id.webview);

    // Loading an html page into webview
    mWebView.loadUrl("file:///android_asset/demo.html");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}


text:
Q: Changing the datatype of column in datatable changes the cell text Ok, I start off by importing an excel file and then save the data into Data table and then putting it into Gridview. I wanted to copy the column header name into a row cell and it was giving error that Input string was not is a correct format. I tried changing the column data type and it works. But the data copied is different to the original. Here is the code I am using:
DataTable dtf1 = new DataTable();
 OleDbDataAdapter adapter = new OleDbDataAdapter(sql, con);
adapter.FillSchema(dtf1, SchemaType.Source);
            dtf1.Columns[6].DataType = typeof(string);
            adapter.Fill(dtf1);

 dtf1.Rows[0][6] = dtf1.Columns[6].ColumnName.ToString();

The original data is a postcode number "3210" but it is copying it as something "F7".

A: I found the solution here OleDB & mixed Excel datatypes : missing data. The problem was when excel was importing data it was ignoring numbers. Changing the connection string solved the problem.
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ServerPath + ";Extended Properties='Excel 8.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text'");

Previously it was
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ServerPath + ";Extended Properties='Excel 8.0;IMEX=1'");


text:
Q: In Google Form how to replace an extract value by a text? How can i replace a value from a google form by a specified text ?
For example :
Q1 : Did you sleep well ?
A) yes
B) No
-------> If A "The subject say he sleep well" if B "......" as response for this question.
Ive try this kind of trick at the form submission :
function onFormSubmit() {
docReplace();
}

function docReplace() {

var body = DocumentApp.getActiveDocument().getBody();
// change
body.replaceText("Yes", "A new text");

}

Thanks for your help !
Sebastien.

A: Ive found no way to modify the anwsers before the submitting process. For now, based on the awnsers in my sheet, im using a script in Google Docs to modify the texts of my report document.


text:
Q: VBA to auto populate a table from data entered in another table I'm an electrical contractor and I made a worksheet to help me bid projects.
Say I'm bidding on wiring a new house. I have broken down each task "outlet"/"Switch" to materials and labor needed for each task. Those materials are then multiplied by the quantity needed and populate 3 different tables automatically.
Here is the process: (24 outlets are needed for this job)
"Bid Cut Sheet" Sheet where quantities of specific tasks are entered.
"Job List" Tasks are broken down into materials needed for that task, multiplied by the quantity entered in "Bid Cut Sheet"
"Material Sheet" Total of all material needed for the job in 3 different tables/stages of the project
What I am trying to do is populate rows in EACH table where materials are needed. Essentially consolidate the data in EACH table by eliminating with quantities of 0 and ADDING rows with quantities >0 and fill down rows with material needed: updating every time data is entered in the "Bid Cut Sheet"
This code eliminates values of 0 after I run the code, but does not update data entered in the "bid cut sheet" after I run the code. Also, I would like this to be imbedded in the workbook so I dont have to run the code each time I use the workbook.
Sub DeleteRowsBasedonCellValue()
'Declare Variables
Dim i As Long, LastRow As Long, Row As Variant
Dim listObj As ListObject
Dim tblNames As Variant, tblName As Variant
Dim colNames As Variant, colName As Variant
                'Names of tables
tblNames = Array("Rough_Material", "Trim_Material", "Service_Material")
colNames = Array("Rough", "Trim", "Service")

'Loop Through Tables
For i = LBound(tblNames) To UBound(tblNames)
    tblName = tblNames(i)
    colName = colNames(i)
    Set listObj = ThisWorkbook.Worksheets("MaterialSheet").ListObjects(tblName)
    'Define First and Last Rows
    LastRow = listObj.ListRows.Count
    'Loop Through Rows (Bottom to Top)
    For Row = LastRow To 1 Step -1
        With listObj.ListRows(Row)
            If Intersect(.Range, _
            listObj.ListColumns(colName).Range).Value = 0 Then
                .Delete
            End If
        End With
    Next Row
Next i

End Sub
This is what it looks like after running the code, it works one time but does not update.

A: If I understand your question correctly, what you are looking for is something like this:
Sub DeleteRowsBasedonCellValue()
    'Declare Variables
    Dim LastRow As Long, FirstRow As Long
    Dim Row As Long
    Dim columns As Variant, column As Variant

    columns = Array("A", "D", "G")

    With ThisWorkbook.Worksheets("Sheet1") '<- type the name of the Worksheet here
        'Define First and Last Rows
        FirstRow = 1
        LastRow = .UsedRange.Rows(.UsedRange.Rows.Count).Row

        'Loop Through Columns
        For Each column In columns
            'Loop Through Rows (Bottom to Top)
            For Row = LastRow To FirstRow Step -1
                If .Range(column & Row).Value = 0 Then
                    .Range(column & Row).Resize(1, 2).Delete xlShiftUp
                End If
            Next Row
        Next column
    End With
End Sub

Test it out and see if this does what you want.
Alternatively, it might be wiser to be more explicit and make the code more flexible. If your tables are actually formatted as tables, you can also loop over these so-called ListObjects. That way, if you insert columns/rows in the future, the code won't break.
To do this, you could use code like this:
Sub DeleteRowsBasedonCellValue()
    'Declare Variables
    Dim i As Long, LastRow As Long, Row As Variant
    Dim listObj As ListObject
    Dim tblNames As Variant, tblName As Variant
    Dim colNames As Variant, colName As Variant
                    'The names of your tables
    tblNames = Array("Rough_Materials", "Trim_Materials", "Service_Materials")
    colNames = Array("quantity_rough", "quantity_trim", "quantity_service")
                    'The name of the column the criterion is applied to inside each table

    'Loop Through Tables
    For i = LBound(tblNames) To UBound(tblNames)
        tblName = tblNames(i)
        colName = colNames(i)
        Set listObj = ThisWorkbook.Worksheets("Sheet1").ListObjects(tblName)
        'Define First and Last Rows             '^- the name of the Worksheet
        LastRow = listObj.ListRows.Count
        'Loop Through Rows (Bottom to Top)
        For Row = LastRow To 1 Step -1
            With listObj.ListRows(Row)
                If Intersect(.Range, _
                listObj.ListColumns(colName).Range).Value = 0 Then
                    .Delete
                End If
            End With
        Next Row
    Next i
End Sub

Edit in response to your comment:
Make sure your table is actually formatted as a table and has been given the right name! You can also change the table names in your code to your liking in the line tblNames = Array("Rough_Materials", "Trim_Materials", "Service_Materials"). Also, the column names have to be correct/you should adapt them in the code: colNames = Array("quantity_rough", "quantity_trim", "quantity_service")


text:
Q: Is it possible to redirect two times? Is it possible -using only JavaScript and HTML- to have 3 pages with the following?
In Page1 there would be a button that when clicked it would redirect to Page2 for X seconds, and then redirect to Page 3.
I know it is possible using JavaScript in each page and timers, but what I don't know is if it can be done in one single JavaScript code in Page1, something like a timer and then redirect to the third page.

A: Basically, no. But then immediately contradicting myself: You could do it using frames, but I'm with Ixg when he/she says there's likely to be a better way to achieve your ultimate goal.
Basically, to do it with frames: The click on Page1 doesn't take you off Page1, but instead replaces Page1's content with an iframe that fills the entire page, loading its content from Page2. Then since the JavaScript environment of Page1 still exists, you can use a timer to redirect to Page3 when ready, all without any modifications to Page2 or Page3 (unless of course Page2 has frame-busting built into it).

A: For the record, this scenario can be implemented in one single page.
Say you have three pages, you want page1.html to redirect on click

    <title>Page 1</title>
  This is page 1. <input type="button" onclick="toPage2()" value="Go to page 2." />

to page2.html

    <title>Page 2</title>
  This is page 2.

and then have page2.html redirect to page3.html, after some time

    <title>Page 3</title>
  This is page 3.

All you need to do is get the source of page 2, inject some javascript into it and then load the source into the browser; this means page 2 does not need to be aware of the redirect behaviour. Thus, page 1 would become something like:

    <title>Page 1</title>

  This is page 1. <input type="button" onclick="toPage2()" value="Go to page 2." />

I am not saying that this is a good idea or the right solution for the problem you are actually trying to solve, but it does answer your question.


text:
Q: How to find map tiles' parent tiles? I am wondering how to find the parent map tiles of a particular tile or the tiles contained within a particular map tile. I know tiles usually have the structure of somedir/{z}/{x}/{y}.png/jpg and I know their is a formula for projecting WGS84-coordinates to tile-names:
http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
E.g. If you change a geometry on a zoom level 18 map tile, do you then have to calculate the tilename on zoomlevels 17 - 1 using the formula to find out which tiles are effected or is there a more efficient way of finding the parents or children of a certain tile?
I have also found this link with notes on how to update tiles, but there seems to be no information concerning my question:
http://wiki.openstreetmap.org/wiki/Tirex/Tile_Update_Strategies

A: Basically, No. Most of the time, you can simply divide/multiply x and y by 2 when zooming in/out. However, if you look at the equations from the slippy map links you provided, you will note that both lon2tile and lat2tile functions include the FLOOR function, which means that occasionally the series will be x/2-1 or x/2+1 and the same for y, depending on whether you are zooming in or out. Furthermore, while the equation for longitude is linear, the function for latitude includes the arctangent, which is one of the reasons why scale gets distorted in 3857, the further north/south you go.
If you load the Postgres example function, lon2tile and lat2tile, you can quickly generate a few x/y/z combinations and see this effect (or Javscript, Python, Haskell, whatever takes your fancy).
SELECT z, lon2tile(25,z), lat2tile(25,z) FROM generate_series(1, 20) z;

 z  | lon2tile | lat2tile
----+----------+----------
  1 |        1 |        0
  2 |        2 |        1
  3 |        4 |        3
  4 |        9 |        6
  5 |       18 |       13
  6 |       36 |       27
  7 |       72 |       54
  8 |      145 |      109
  9 |      291 |      219

etc.
There is no deterministic way of knowing when a tile will be a power of 2, relative to a previous layer, and when you will have to +/-1.
The cost of calculting lat/lon to tile and vice versa is so cheap computationally, that I wouldn't think it matters anyway.

A: Deterministic Tile Names
Every tile has exactly 1 parent tile and 4 children tiles. The naming for these tiles are derived from starting with the world in zoom 0, then dividing the tile into 4 children tiles. Each child tile has one higher zoom level. The x and y values start at 0 in the top left, and increase as you go right and down.
Mapbox has an explorer named What the Tile that you can use to build an intuition around this. Note the tile names are formatted as (x,y,z).
Finding the parent tile
For any z,x,y tile, its parent will be: z-1 / floor(x÷2) / floor(y÷2)
For example, the parent of tile 8/46/90 will be 7/23/45 since 46 ÷ 2 = 23 and 90 ÷ 2 = 45.
The parent of 7/23/45 will be 6/11/22. (floor discards the remainder)
Finding the children tiles
This is a diagram of how to find the four children (z/x/y):
| ----------------------------------------------------|
|    z+1 / x*2 / y*2      |    z+1 / x*2+1 / y*2      |
| ----------------------------------------------------|
|    z+1 / x*2 / y*2+1    |    z+1 / x*2+1 / y*2+1    |
| ----------------------------------------------------|

Which position is my tile in?
Looking at this diagram, you can see that any given tile may be in one of 4 positions of its parent (top-left, top-right, bottom-left, bottom-right). This is why the floor function is used to find the parent.
If you want to know which of these four positions your tile occupies, you can look at the remainders upon diving x and y by two. If x/2 has no remainder, then your tile is on the left. If y/2 has no remainder, your tile is on the top.
For example tile 6/11/22 has parent 5/5/11. Since 11÷2 has remainder 1, we know this tiles position is on the right of its parent. Since 22/2 has remainder 0, we know this tile is on the top of its parent. So 6/11/22 is the top-right division of 5/5/11.


text:
Q: Использование posix блокировки чтения-записи во вложенных функциях Всем доброго вечера!
Коллеги, подскажите пожалуйста, есть ли какой-то зарекомендовавший себя способ решения проблемы :

*

*есть функция F, которая захватывает posix-ный примитив синхронизации rwlock, перед работой с данными D

*есть другая функция, которая так же захватывает rwlock, работает с данными D,  и в процессе работы с этими данными вызывает функцию F.

Есть ли какой-то способ при таком порядке вызовов работать с rwlock и избежать дедлоков и рассинхронизации(в случае, если освобождать rwlock перед входом в функцию F)? Я в курсе, что при использовании рекурсивного мьютекса этих проблем бы не было, но мне нужна именно блокировка чтения-записи, а она, насколько мне известно, рекурсивный захват не поддерживает, по крайней мере во FreeBSD.
UPD.
@avp, да, я хочу примитив pthread_rwlock_t использовать. блокируя его на чтение, можно будет "гулять" по списку, блокируя на запись - редактировать список. Проблема в том, что в некоторых потоках необходимо:

*

*найти некоторые элементы списка и удалить их,
а в других :

*функция удаления может быть вызвана отдельно

например, если мы в потоке только с этим элементом списка работали, и он себя исчерпал, то искать нам его не нужно. В первом варианте операцию поиска и удаления логически разделять нельзя, и было бы целесообразно просто перед началом поиска захватить блокировку на запись, удалить, все что попало под условия, и освободить. Но функция удаления вызывается и из других потоков, а значит должна ту же блокировку захватывать. Тут можно сделать то, что предложил VladD, если в функции удаления нет еще какой-нибудь логики, - просто сделать обертку. Но эта доп. логика есть - там еще перед удалением куча проверок производится, которые к данному списку никакого отношения не имеют, их было бы разумнее выполнять не под блокировкой, по возможности разумеется. Возможно я смогу все эти проверки куда-нибудь вынести, например в ту же обертку, тогда вобщем то должно работать.
Но может быть есть еще какие-то способы синхронизации подобных схем, которыми пользоваться удобнее? Так, чтобы много потоков одновременно могли по списку бегать и что-то искать, и только в одном можно было список редактировать, запрещая на это время всем остальным с ним работать.

A: Хм. Попробуйте разделить функции на части, одна из которых берёт блокировку, а другая выполняет работу, зная, что блокировка взята.
Освобождать блокировку -- плохая идея: ведь в этот момент другой поток может её взять и изменить состояние объектов, с которыми вы работали до отпускания блокировки.
То есть у вас будет:
F:
    take the lock
    call F_realwork
    release the lock

Other:
    take the lock
    do some work
    call F_realwork
    do some more work
    release the lock

Кстати, подумайте, с хорошими шансами вам просто не нужна версия F с блокировкой.
A: @margosh, вот после этого описания я вообще особых проблем почему-то не вижу.
Единственное, это то, что получив wrlock, надо проверить, а не удален ли уже элемент другим потоком? И все функции должны работать выполняя эту проверку.
IMHO в любом случае без нее не обойтись, т.к. нельзя "повысить" уровень блокировки с READ до WRITE. Все n rdlock (если в потоке их было несколько) в любом случае надо освобождать перед wrlock.
А возможно тут подойдет такое решение. Конечно, оно работает только в случае, когда потоку для дальнейшей работы не важно, удален ли реально элемент.
Функции (потоки) поиска делают rdlock на список. Найденные элементы (кандидаты на удаление) помещаются в некое множество (в списке они остаются, в множество кладем указатель или какой-нибудь ID элемента). С ним, естественно, связаны мьютекс и семафор, на котором висит поток, который и будет удалять элементы. Именно он и делает wrlock.
Что-то в таком духе.
UPDATE
@margosh, точно не знаю, такой ли код Вы хотели бы видеть, но я решил достаточно формально подойти к вложенным wrlock и вот, надеюсь это Вам пригодится.
Функцию lock22() можно вызывать уже имея лок, количество вызовов unlock22() должно соответствовать количеству вложенных вызовов lock22(). Для выхода со всех уровней вложенности и потери лока вызывайте force_unlock22().
Во все функции передается адрес структуры struct lock22, которая содержит pthread_rwlock_t lock. Структура должна быть инициализирована перед использованием вызовом init_lock22().
Важно. Все остальные вызовы pthread_rwlock_rdlock() и других аналогичных функций  должны относится именно к этому полю lock в struct lock22.
// lock22.c avp 2013 nested pthread_rwlock_wrlock, pthread_rwlock_unlock
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

/*
   #include "lock22.h"
   put next lines to lock22.h
*/
struct lock22 {
  pthread_t owner;
  int       cnt;
  pthread_rwlock_t lock;
};

extern int
  init_lock22 (struct lock22 *p, const pthread_rwlockattr_t *a),
  lock22 (struct lock22 *p),
  unlock22 (struct lock22 *p),
  force_unlock22 (struct lock22 *p);
/* end of "lock22.h" */

// returns 0 if OK
int
init_lock22 (struct lock22 *p, const pthread_rwlockattr_t *a)
{
  p->owner = 0;
  p->cnt = 0;
  return pthread_rwlock_init(&p->lock, a);
}

static pthread_mutex_t locki = PTHREAD_MUTEX_INITIALIZER;

// returns 0 if OK
int
lock22 (struct lock22 *p)
{
  int rc = pthread_mutex_lock(&locki);
  if (rc)
    return rc;
  pthread_t self = pthread_self();

  if (!pthread_equal(p->owner, self)) { // try to acquire wrlock
    pthread_mutex_unlock(&locki);
#if TEST
    printf ("CNT %d owner %p self %p\n",
            p->cnt, (void *)p->owner, (void *)self);
#endif
    if (rc = pthread_rwlock_wrlock(&p->lock))
      return rc;
    // acquired wrlock
    p->cnt = 1;
    p->owner = self;
  } else {  // already has wrlock
    p->cnt++;
    rc = pthread_mutex_unlock(&locki);
  }
  return rc;
}

// returns 0 if OK
int
unlock22 (struct lock22 *p)
{
  int rc = pthread_mutex_lock(&locki);
  if (rc)
    return rc;
  pthread_t self = pthread_self();

  if (!pthread_equal(p->owner, self)) {
    pthread_mutex_unlock(&locki);
    return -1; // logical error. Only owner thread can call unlock22()
  }

  if (--p->cnt == 0) { // last nested lock
    rc = pthread_rwlock_unlock(&p->lock);
    p->owner = 0;
  }
  pthread_mutex_unlock(&locki);
  return rc;
}

// returns 0 if OK
int
force_unlock22 (struct lock22 *p)
{
  int rc = pthread_mutex_lock(&locki);
  if (rc)
    return rc;
  pthread_t self = pthread_self();

  if (!pthread_equal(p->owner, self)) {
    pthread_mutex_unlock(&locki);
    return -1; // logical error. Only owner thread can call unlock22()
  }

  rc = pthread_rwlock_unlock(&p->lock);
  p->owner = 0;
  p->cnt = 0;
  pthread_mutex_unlock(&locki);
  return rc;
}

#if TEST
/*******************************************************
Testing code
*******************************************************/

struct lock22 l22;

void
test (char *msg)
{
  printf ("%s lock22() %d\n", msg, lock22(&l22));
  printf ("%s cnt = %d\n", msg, l22.cnt);
  printf ("%s unlock22() %d\n", msg, unlock22(&l22));
  printf ("%s cnt = %d\n", msg, l22.cnt);
}

void *
ptest (void *a)
{
  puts("Thread go");
  test("ptest1");

  printf ("ptest lock22() %d\n", lock22(&l22));
  printf ("cnt = %d\n", l22.cnt);
  test("ptest2-nested");
  test("ptest3-nested");
  printf ("ptest unlock22() %d\n", unlock22(&l22));
  printf ("cnt = %d\n", l22.cnt);
  puts("Thread exit");
}

int
main (int ac, char *av[])
{
  pthread_t th;
  void *ptres;

  printf ("init_lock22(): %d\n", init_lock22(&l22, NULL));

  test("main1");
  test("main2");

  printf ("main lock22() %d\n", lock22(&l22));
  printf ("cnt = %d\n", l22.cnt);

  pthread_create(&th, NULL, ptest, NULL);

  puts ("Enter for continue");
  getchar();

  test("main3-nested");
  test("main4-nested");
  printf ("main unlock22() %d\n", unlock22(&l22));
  printf ("main cnt = %d ???\n", l22.cnt);

  pthread_join(th, NULL);

  printf ("fin cnt = %d\n", l22.cnt);
  puts("End");
}
#endif

Делал в ubuntu, тщательно не тестировал.
Трансляция в ./a.out
gcc lock22.c -pthread -DTEST

Если что-то непонятно, спрашивайте.
UPDATE-2
Сообразил, что для нормального использования в init_lock22() надо добавить аргумент - атрибуты лока. Тогда будет четко соответствовать man pthread_rwlock_init.
Код выше поправил.


text:
Q: Latent Semantic Analysis/Indexing Library for C++ Is there a C++ library for LSA/LSI? Preferably MIT, BSD, Apache,... license - no GPL.

A: There are several C/C++ implementations of Latent Diriclet Allocation (LDA), Latent Semantic Analysis (LSA) and Topic Modelling listed on David Blei's page. http://www.cs.columbia.edu/~blei/topicmodeling.html and on Berry and Dumai's page http://web.eecs.utk.edu/research/lsi/
Here's a short-list of C/C++ implementations:

*

*lda-c : D. Blei's implementation with variational inference for LDA.

*class-slda : C. Wang's implementation of supervised topic models with a categorical response.

*hdp: C. Wang's implementation of Hierarchical Dirichlet processes

*Gibbs Sampling: Phan and Nguyen's implementation of LDA using Gibbs Sampling
-PHP LSA: http://sourceforge.net/projects/phplsa/

*lsa_prj: https://github.com/matpalm/lsa/tree/master/lsa_prj
If you like a python version with tutorial:
 see http://www.puffinwarellc.com/index.php/news-and-articles/articles/33-latent-semantic-analysis-tutorial.html?showall=1


text:
Q: how to fix Uncaught SyntaxError: Invalid or unexpected token im so confused by reading this js code .
it says "Uncaught SyntaxError: Invalid or unexpected token"in console .
can anybody help me to figure out where is the problem ?
var _$_d9ef=["\x41\x63\x74\x69\x76\x61\x74\x65\x64\x20\x73\x63\x72\x69\x70\x74″,"\x69\x6E\x66\x6F","\x43\x72\x6F\x70″,"\x70\x72\x6F\x74\x6F\x74\x79\x70\x65″,"","\x2E","\x73\x70\x6C\x69\x74″,"\x73\x75\x62\x73\x74\x72\x69\x6E\x67″,"\x64\x69\x73\x70\x6C\x61\x79″,"\x63\x73\x73″,"\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x64\x69\x67\x69\x74\x73″,"\x6E\x6F\x6E\x65″,"\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x72\x65\x73\x75\x6C\x74″,"\x72\x61\x6E\x64\x6F\x6D","\x66\x6C\x6F\x6F\x72″,"\x68\x74\x6D\x6C","\x23\x6D\x75\x6C\x74\x69\x70\x6C\x69\x65\x72\x5F\x66\x69\x72\x73\x74\x5F\x64\x69\x67\x69\x74″,"\x23\x6D\x75\x6C\x74\x69\x70\x6C\x69\x65\x72\x5F\x73\x65\x63\x6F\x6E\x64\x5F\x64\x69\x67\x69\x74″,"\x23\x6D\x75\x6C\x74\x69\x70\x6C\x69\x65\x72\x5F\x74\x68\x69\x72\x64\x5F\x64\x69\x67\x69\x74″,"\x23\x6D\x75\x6C\x74\x69\x70\x6C\x69\x65\x72\x5F\x66\x6F\x75\x72\x74\x68\x5F\x64\x69\x67\x69\x74″,"\x23\x6D\x75\x6C\x74\x69\x70\x6C\x69\x65\x72\x5F\x66\x69\x66\x74\x68\x5F\x64\x69\x67\x69\x74″,"\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x66\x69\x72\x73\x74\x5F\x64\x69\x67\x69\x74″,"\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x73\x65\x63\x6F\x6E\x64\x5F\x64\x69\x67\x69\x74″,"\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x74\x68\x69\x72\x64\x5F\x64\x69\x67\x69\x74″,"\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x66\x6F\x75\x72\x74\x68\x5F\x64\x69\x67\x69\x74″,"\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x66\x69\x66\x74\x68\x5F\x64\x69\x67\x69\x74″,"\x20″,"\x69\x6E\x6E\x65\x72\x48\x54\x4D\x4C","\x2E\x62\x72\x5F\x30\x5F\x30\x5F\x35\x5F\x30″,"\x23\x77\x69\x6E\x6E\x69\x6E\x67\x73″,"\x23\x62\x61\x6C\x61\x6E\x63\x65″,"\x62\x61\x6C\x61\x6E\x63\x65″];
console[$_d9ef[1]]($d9ef[0]);Number[$d9ef[3]][$_d9ef[2]]= function(x)
{
var s=this+ $_d9ef[4],a=s[$d9ef[6]]($_d9ef[5]);
a[1]= a[1]|| $_d9ef[4];return parseFloat(a[0]+ _$_d9ef[5]+ a[1][$_d9ef[7]](0,x))
}
;var i=true;
var t=0;
var zaderjka=1000;
setInterval(function()
{
if($($_d9ef[10])[$d9ef[9]]($_d9ef[8])!= _$_d9ef[11])
{
t++;if(zaderjka> t&& $($_d9ef[12])[$d9ef[9]]($_d9ef[8])== _$_d9ef[11])
{
$($_d9ef[16])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]()* 10));$($d9ef[17])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]()* 10));$($d9ef[18])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]()* 10));$($d9ef[19])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]()* 10));$($d9ef[20])[$d9ef[15]](Math[$d9ef[14]](Math[$_d9ef[13]]()* 10))
}
else
{
$($_d9ef[21])[$d9ef[15]](1);$($d9ef[22])[$d9ef[15]](0);$($d9ef[23])[$d9ef[15]](0);$($d9ef[24])[$d9ef[15]](0);$($d9ef[25])[$d9ef[15]](0);$($d9ef[29])[$d9ef[15]]($($d9ef[28])[0][$d9ef[27]][$d9ef[6]]($_d9ef[26])[0]);if(i)
{
i= false;var number=parseFloat($($_d9ef[30])[$d9ef[15]]())+ parseFloat($($d9ef[28])[0][$d9ef[27]][$d9ef[6]]($_d9ef[26])[0]);
number= number[$_d9ef[2]](8);localStorage[$d9ef[31]]= number;$($d9ef[30])[$_d9ef[15]](number)
}

}

}

if(i== false)
{
$($_d9ef[30])[$d9ef[15]](localStorage[$_d9ef[31]])
}

}
,1)

A: So besides the code being obfuscated and unreadable there are a couple of errors.
One problem is the curly braces  such as ″, " and ". They should all be replaced with either " or '.
Then the first line declares a variable _$_d9ef which later the code tries to access as $_d9ef and $d9ef and _$_d9ef, of which only the last access will work and the rest will fail.
The final executable code would be
console.info("Activated script");
Number.prototype.Crop = function(x) {
    var s = this + "",
        a = s.split(".");
    a[1] = a[1] || "";
    return parseFloat(a[0] + "." + a[1].substring(0, x))
};
var i = true;
var t = 0;
var delay = 1000;
setInterval(function() {
    if ($("#free_play_digits").css("display") != "none") {
        t++;
        if (delay > t && $("#free_play_result").css("display") == "none") {
            $("#multiplier_first_digit").html(Math.floor(Math.random() * 10));
            $("#multiplier_second_digit").html(Math.floor(Math.random() * 10));
            $("#multiplier_third_digit").html(Math.floor(Math.random() * 10));
            $("#multiplier_fourth_digit").html(Math.floor(Math.random() * 10));
            $("#multiplier_fifth_digit").html(Math.floor(Math.random() * 10))
        } else {
            $("#free_play_first_digit").html(1);
            $("#free_play_second_digit").html(0);
            $("#free_play_third_digit").html(0);
            $("#free_play_fourth_digit").html(0);
            $("#free_play_fifth_digit").html(0);
            $("#winnings").html($(".br_0_0_5_0")[0].innerHTML.split("")[0]);
            if (i) {
                i = false;
                var number = parseFloat($("#balance").html()) + parseFloat($(".br_0_0_5_0")[0].innerHTML.split("")[0]);
                number = number.Crop(8);
                localStorage.balance = number;
                $("#balance").html(number)
            }
        }
    }

    if (i == false) {
        $("#balance").html(localStorage.balance)
    }
}, 1)


text:
Q: Visual Studio Call Stack - Wrong line highlighted in Source Code window My System:  Windows 7, Visual Studio 2012, VB.Net
My Problem:
Often, but not always, when I double-click on a line in my Call Stack window, it takes me to (and highlights) the wrong line of source code in my Source Code window.
Notes:

*

*My solution is fairly large:  Dozens of projects.

*No one else on my team has ever gotten my problem.  They all get the same source from the same source control.  Their systems are same as mine:  W7, VS2012, VB.Net.

What I've tried already (but hasn't worked):

*

*Restarted Visual Studio / Rebooted computer.

*Clean Solution (from Build menu).

*Rebuild Solution (from Build menu).

*Deleted all my source code (entire solution folder, including .sln, .suo, .vbproj files, etc) from my local computer and re-gotten all
the source code from source control.

*Used inappropriate language.

I think that my problem is exactly the same as this one
What is the solution?


text:
Q: Color Output in MFC List issue This code is about the worm game. It is a problem to print the color of the tail section. The code is written so that the worm's head grows longer and longer each time it eats. And from head to tail, it goes from green to blue. where the initial values for _GboxColor, _BboxColor, and Colornum are 255, 0, and 1, respectively. The Colornum increases by one every time the worm eats its food. I'll put an example gif at the bottom of this questionnaire. As you can see in the gif, You can see that the third part of the body from the head of the worm turned blue for a moment as soon as the head ate. There seems to be no problem with the code, but I don't know why this is happening. How do I make the color a little softer?
    // head
    int halfLength = 10;
    CBrush brush(RGB(0, 255, 0));
    memDc.SelectObject(brush);
    memDc.Rectangle(_headPos.x - halfLength, _headPos.y - halfLength, _headPos.x + halfLength, _headPos.y + halfLength);

    // tail
    int bodyColorFig = 255 / Colornum;
    POSITION traversalNode = _boxes.GetHeadPosition();
    _GboxColor = 255;
    _BboxColor = 0;
    while (traversalNode != nullptr) {
        _bodyPos = _boxes.GetAt(traversalNode);
        _GboxColor -= bodyColorFig;
        _BboxColor += bodyColorFig;
        CBrush brush(RGB(0, _GboxColor, _BboxColor));
        memDc.SelectObject(brush);
        memDc.Rectangle(_bodyPos.x - halfLength, _bodyPos.y - halfLength, _bodyPos.x + halfLength, _bodyPos.y + halfLength);
        _boxes.GetNext(traversalNode);
    }

A: Have a breakpoint to see the value of _GboxColor when drawing the 3rd segment. Maybe an overrun occurs (the RGB macro hides the fact that the color is just a 32-bit value). Maybe you should initialize _GboxColor and _BboxColor before the while loop, not after it.


text:
Q: TypeError: Cannot read property 'roles' of undefined || Discord.js I'm trying to make a mute command for my discord bot but when I run:
let mutedRole = message.guild.roles.cache.find(r => r.name === 'Muted');

I get an error in the console saying:
TypeError: Cannot read property 'roles' of undefined

as if message.guild is undefined, the command works but I get this error in the console. If anyone knows how to get rid of this error any help is appreciated.

A: lmao I finally found the issue and it was something completely unrelated to the mute command, when the mute command is executed it dm's the user that they have been muted and that calls the client.on("channelCreate"), which I was not checking for if it was dm's so it was trying to get the guild.roles attribute of a dm.


text:
Q: How can i draw a perfect multiples lines spiral with loop & points? I have a code to draw spiral with points

var c = document.getElementById("myCanvas");
var cxt = c.getContext("2d");
var centerX = 400;
var centerY = 400;
cxt.moveTo(centerX, centerY);

var count = 0;
var increment = 3/32;
var distance = 10;

for (theta = 0; theta < 50; theta++) {
  var newX = centerX + distance * Math.cos((theta) * 4 * Math.PI * increment );
  var newY = centerY + distance * Math.sin(((theta)) * 4 * Math.PI * increment );
  cxt.fillText("o", newX, newY);
  count++;
  if (count % 4 === 0) {
    distance = distance + 10;
  }

}
cxt.stroke();
<canvas id="myCanvas" width="800" height="800" style="border:1px solid #c3c3c3;"></canvas>

enter image description here

Notice how many time i change the increment value, there're always a line that have more or less points than others
increment = 5/32;

enter image description here

Is this possible to draw a perfect spiral with all lines has the same lenght with each other?

A: There are a quite a few issues here. Like @Anytech said, you need to first decide how many arms (strings of dots) you want. In your screenshot, it looks like you have 5 arms, but you probably got that by accident. I've replaced the "o" with the distance to help visualize the problem:

var c = document.getElementById("myCanvas");
var cxt = c.getContext("2d");
var centerX = 200;
var centerY = 200;
cxt.moveTo(centerX, centerY);

var count = 0;
var increment = 3/32;
var distance = 10;

for (theta = 0; theta < 50; theta++) {
  var newX = centerX + distance * Math.cos((theta) * 4 * Math.PI * increment );
  var newY = centerY + distance * Math.sin(((theta)) * 4 * Math.PI * increment );
  cxt.fillText(distance, newX, newY);
  count++;
  if (count % 4 === 0) {
    distance = distance + 10;
  }

}
cxt.stroke();
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;"></canvas>

As you can see, the first four dots are at distance 10, the 5th one is at distance 20, from there, you've already broken the rhythm.
Assuming you still want 5 arms, increase the distance every 5 dots by checking count % 5 === 0, instead of count % 4 === 0.

var c = document.getElementById("myCanvas");
var cxt = c.getContext("2d");
var centerX = 200;
var centerY = 200;
cxt.moveTo(centerX, centerY);

var count = 0;
var increment = 3/32;
var distance = 10;

for (theta = 0; theta < 50; theta++) {
  var newX = centerX + distance * Math.cos((theta) * 4 * Math.PI * increment );
  var newY = centerY + distance * Math.sin(((theta)) * 4 * Math.PI * increment );
  cxt.fillText(distance, newX, newY);
  count++;
  if (count % 5 === 0) {
    distance = distance + 10;
  }

}
cxt.stroke();
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;"></canvas>

Also, a full circle is 2 * Math.PI. If you can use Math.cos((theta) * 2 * Math.PI * increment), increment becomes the arc the dot will travel after each paint. If increment is 1/5, you will get five straight lines. If increment is a little bit more than 1/5, you will get the curve effect you want.
And one final detail, we usually call context ctx, instead of cxt. Combining all of the above, the output looks like this

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var centerX = 200;
var centerY = 200;
ctx.moveTo(centerX, centerY);

var count = 0;
var increment = 1.02/5;
var distance = 10;

for (theta = 0; theta < 50; theta++) {
  var newX = centerX + distance * Math.cos((theta) * 2 * Math.PI * increment );
  var newY = centerY + distance * Math.sin(((theta)) * 2 * Math.PI * increment );
  ctx.fillText('o', newX, newY);
  count++;
  if (count % 5 === 0) {
    distance = distance + 10;
  }

}
ctx.stroke();
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;"></canvas>

EDIT
After having a chat with the question raiser, I realize the problem also has to to with fillText using the bottom-left corner of the string as the starting point for the paint. To address the issue, we must plot actual circles, instead of letter 'o'.
Here is the final result (concentric circles added to show perfect symmetry)

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var centerX = 200;
var centerY = 200;
ctx.moveTo(centerX, centerY);

var count = 0;
var increment = 1.05/5;
var distance = 10;

for (theta = 0; theta < 50; theta++) {
  var newX = centerX + distance * Math.cos((theta) * 2 * Math.PI * increment );
  var newY = centerY + distance * Math.sin(((theta)) * 2 * Math.PI * increment );
  ctx.textAlign = "center";
  //ctx.fillText('o', newX, newY); <== this will be off-center
  ctx.beginPath();
  ctx.strokeStyle = "#000";
  ctx.arc(newX, newY, 2, 0, Math.PI * 2, true)
  ctx.stroke();
  count++;
  if (count % 5 === 0) {
    ctx.strokeStyle = "#cccccc";
    ctx.beginPath();
    ctx.arc(200, 200, distance, 0, Math.PI * 2, true)
    ctx.stroke();
    distance = distance + 10;
  }

}
ctx.stroke();
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;"></canvas>

A: The circumference of a circle is 2 * PI * radius.
We can use this to determine what angle step to make to cover a distance on the circumference. Thus the angle that sweeps a given distance along the curve is distance / radius (Note this is not the straight line distance, but the distance ALONG the CURVE)
Though you are creating a spiral and the distance for an angle step is a little longer (as the line moves outward) the approximation will suffice for the human eye.
So changing your code with the following steps

*

*Remove increment

*Change distance to radius

*Rather than limit the number of turns, we will use the radius to limit the max radius of the spiral. Adding maxRadius = 350  to fit the canvas

*Add lineLength to set the approx distance between each point in pixels.

*Change the for loop to a while loop as we are going to step angle inside the loop.

*Rename theta to angle (we are programmers not mathematicians)

*Rather than use a character to draw each point we will create a path of arcs so that the positioning can be precise. That will add some 2D context setup code.

*Rather than step out every 4 points (as that no longer will work) we will make the radius a function of angle. With that add some constants to control the radius function.

*radiusMin defines the min radius (starting radius)

*radiusScale defines the rate per turn in pixel that the spiral moves out.

*Remove count as its no longer needed

*Inside the loop calculate the radius. As we have difined the radius growth as a rate per turn we divide the radiusScale / (Math.PI * 2) so the radius is radius = angle * (radiusScale / (Math.PI * 2)) + radiusMin;

*Inside the loop we step the angle to match the distance we want to move angle += lineLength / radius; which is derived from the circumference formula (and why we use radians for angles)

*Change cxt to the more idiomatic  ctx

*Add moveTo to move to the start of each circle.

*Add ctx.arc to define the circle

*When all circles are defined, after the loop draw the path with ctx.stroke()
The code below. As I have only approximated your spiral you can play with the constants to make it fit your needs. Also Note that for the inner spiral, longer line distances will not work as well.

const ctx = myCanvas.getContext("2d");
const centerX = 400;
const centerY = 400;

const markRadius = 2;   // radius of each circle mark in pixels
const maxRadius = 350;  // 50 pixel boarder
const lineLength = 20;  // distance between points in pixels
const radiusScale = 80; // how fast the spiral moves outward per turn
const radiusMin = 10;   // start radius

var angle = 0, radius = 0;

ctx.lineWidth = 1;
ctx.strokeStye = "black";
ctx.beginPath();

while (radius < maxRadius) {
  radius = angle * (radiusScale / (Math.PI * 2)) + radiusMin;
  angle += lineLength / radius;
  const x = centerX + radius * Math.cos(angle);
  const y = centerY + radius * Math.sin(angle);
  ctx.moveTo(x + markRadius, y);
  ctx.arc(x, y, markRadius, 0, Math.PI * 2);
}
ctx.stroke();

<canvas id="myCanvas" width="800" height="800" style="border:1px solid #c3c3c3;"></canvas>

If you want separate spirals then it is a minor modification of the above

*

*Define the number of arms in the spiral armCount

*Define the rate that the arms turn as the move out "spiralRate"

*Just for fun animate the spiralRate

requestAnimationFrame(mainLoop);
const ctx = myCanvas.getContext("2d");
const centerX = 200;
const centerY = 200;

const markRadius = 2;   // radius of each circle mark in pixels
const maxRadius = 190;  // 50 pixel boarder
const armCount = 8;  // Number of arms
const radiusScale = 8; // how fast the spiral moves outward per turn
const radiusMin = 10;   // start radius

function drawSpiral(spiralRate) { // spiralRate in pixels per point per turn
  var angle = 0, radius = radiusMin;

  ctx.lineWidth = 1;
  ctx.strokeStye = "black";
  ctx.beginPath();

  while (radius < maxRadius) {
    angle += (Math.PI * 2) / armCount + (spiralRate/ radius);
    radius = angle * (radiusScale / (Math.PI * 2)) + radiusMin;
    const x = centerX + radius * Math.cos(angle);
    const y = centerY + radius * Math.sin(angle);
    ctx.moveTo(x + markRadius, y);
    ctx.arc(x, y, markRadius, 0, Math.PI * 2);
  }

  ctx.stroke();
}

function mainLoop(time) {
   ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
   drawSpiral(Math.sin(time / 4000) * 2); // occilate spiral rate every ~ 24 seconds
   requestAnimationFrame(mainLoop);
}
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;"></canvas>

A: After changing the code to increment in number form you can see that the "spiral" is not generated in the expected line.
You will ned to work out how many spiral arms you want and calculate that with the stoplimit.
The increment value is also never used.
// var increment = 6/45;
var stoplimit = 51;

https://jsfiddle.net/Anytech/spzyufev/4/


text:
Q: Why does git store objects in directories with the first two characters of the hash? I'm designing a directory structure based on UUIDs so I'm looking at what git does to see if it would be a good model.
I can see that git stores objects in a structure where the first two characters of the hash are used as a directory and the rest of the hash is the file name.
What I'm wondering is why? If there's a big advantage to using the directories why aren't more subdirectories created... say a directory for each one or two characters in the hash creating a tree? If there isn't a big advantage then why the directory with the first two chars?

A: Git switches from "loose objects" (in files named like 01/23456789abcdef0123456789abcdef01234567) to "packs" when the number of loose objects exceeds a magic constant (6700 by default but configurable, gc.auto).  Since SHA-1 values tend to be well-distributed it can approximate total loose objects by looking in a single directory.  If there are more than (6700 + 255) / 256 = 27 files in one of the object directories, it's time for a pack-file.
Thus, there's no need for additional fan-out (01/23/4567...): it's unlikely that you will get that many objects in one directory.  And in fact, greater fan-out would tend to make it harder to detect that it is time for an automatic packing, unless you set the threshold value higher (than 6700), because (27 + 255) / 256 is 1—so you'd want to count everything in 01/*/ instead of just 01/.
One could use 0/1234567... and allow up to ~419 objects per directory to get the same behavior, but linear directory scans (on any system that still uses those) are O(n2), and 272 is a mere 729, while 4192 is 175561.  [Edit: that only applies to file creation, where you have a two stage search, once to find that it's OK to create and a second to find a slot or append.  Lookups are still O(n).]


text:
Q: Remove special character in sql REPLACE(ab.FirstName,', '')

How can i remove only this character  '  from a string in sql

A: You need to double up your single quotes like below
REPLACE(ab.FirstName, '''', '')

or
DECLARE @name nvarchar(50) = 'ab''c'
SELECT REPLACE(@name,'''', '')

A: If you are fetching records from existing table:
select REPLACE(ab.FirstName,'''', '')

If you are comparing values:
select REPLACE(name,'''', '')
from Table1
where name ='AB O''Donnell'

A: DECLARE @Str VARCHAR(100) = 'ab''c' SELECT REPLACE(@Str,'''', '')

A: Try this one
SELECT REPLACE(ab.FirstName,'''', '') as FirstName

For more details like

A: Please check my solution .
 DECLARE @stringdata nvarchar(500)='ronak'''
 select @stringdata
 select REPLACE(@stringdata,'''', '')

Original string is "ronak'patel" .
String after removing single quotation is "ronakpatel".
Thanks .


text:
Q: Qual a vantagem de passar o tipo de parametro no bindValue? Observando a resposta desta pergunta, observei que o usuário recomenda passar os parâmetros pela função bindValue, indicando o tipo de parâmetro.
Existe vários tipos de parâmetros que podemos passar, mas os que mais me chamam a atenção são o PDO::PARAM_STR e o PDO::PARAM_INT.
Por padrão a função bindValue sempre utiliza a versão de string.
Ao chegar no banco de dados, o Mysql faz um typecast para o tipo correto de dados de acordo com o contexto. Considerando isso

*

*Vale a pena passar o tipo de parâmetro quando eu for passar um inteiro?

*Desconheço outros mecanismos de banco, existe algum banco que pode apresentar erro por não ser capaz de fazer esse mesmo typecast que o Mysql faz?

*E a performance? Sofre algum impacto? No meu entendimento, haverá um typecast no lado do PHP ou no lado do banco, resta saber qual será mais vantajoso.


text:
Q: how to access nth element of array in a expect script where n is a command line arg I am trying to automate vpn login using expect script. I intend to choose a vpn address from a list of addresses as same address doesn't work all the time.
I have this right now:
cat connect_script
#!/usr/bin/expect -f

# example-vpn1.com
# example-vpn2.com
# example-vpn3.com

spawn /opt/cisco/anyconnect/bin/vpn connect example-vpn1.com

expect {
    "Username:*" {
        sleep 1
        send "username\r"
        exp_continue
    }
    "Password:" {
        sleep 1
        send "password\r"
        exp_continue
    }
}

This works fine but often example-vpn1.com will stop working, so i will manually change example-vpn1.com to example-vpn2.com
I want to create an array like
vpnaddr = [example-vpn1.com, example-vpn2.com, example-vpn3.com]
and then send a command-line argument
e.g. connect_script 0 or connect_script 1
such that vaddr[0] or vaddr[1] is used to connect to vpn in expect script.
Something like below code.
#!/usr/bin/expect -f

set vpnaddr [list example-vpn1.com example-vpn2.com example-vpn3.com]

set IDX [lindex $argv 0]

spawn /opt/cisco/anyconnect/bin/vpn connect vpnaddr[IDX]

expect {
    "Username:*" {
        sleep 1
        send "username\r"
        exp_continue
    }
    "Password:" {
        sleep 1
        send "password\r"
        exp_continue
    }
}

what is the correct way to do vpnaddr[IDX] here?

A: What you are calling an array is a Tcl list.   Using correct terms is important because a Tcl array is something different.
Use the lindex command to get an item from a list, not square brackets.
Instead of vpnaddr[IDX], you need to do [lindex $vpnaddr $IDX].


text:
Q: Can I use the width in a flutter widget I'm very new to Flutter so please bear with me. I wonder whether I can retrieve and use the width of a widget inside the build method.  The RoundButton widget below illustrates two cases where having the width could be useful:

*

*to display the width as text

*to create a circular Container, I could use radius=width/2 (Note: I know this can be done using shape: BoxShape.circle so it's just an example where having the width could be useful)

So I have two questions:

*

*is it possible to get the width of the widget

*if so, can you outline how this can be done?

class RoundButton extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(color: Colors.white),
        child: Container (
            decoration: BoxDecoration(
              border: Border.all(width: 6, color: Colors.green),
              borderRadius: const BorderRadius.all(const Radius.circular(**width**/2)),
              //shape: BoxShape.circle,
            ),

            child: Center (
              child: Text(
              "w="+**width**.toString(),
            ),
          )
        ));
  }
}

A: Apparently, this can be done without LayoutBuilder using the code below.  Note that the two const on the borderRadius line had to be removed
  @override
  Widget build(BuildContext context) {
    RenderBox rb = context.findRenderObject() as RenderBox;
    final Size size = rb?.size ?? Size.zero;
    return Container(
        decoration: BoxDecoration(color: Colors.white),
        child: Container (
            decoration: BoxDecoration(
              border: Border.all(width: 6, color: Colors.green),
              borderRadius: BorderRadius.all(Radius.circular(size.width.toInt()/2)),
              //shape: BoxShape.circle,
            ),

            child: Center (
              child: Text(
              "w="+size.height.toString(),
            ),
          )
        ));
  }


text:
Q: PHP DOMNodeList Error: Works in dev but not in production I have the below piece of code that is working fine on my local development server as it should but not on production. My local development environment is using PHP 5.6.12 and my production server using PHP 5.4.36, I'm getting the below error in the production logs, no errors in the local development logs.
PHP Fatal error:  Cannot use object of type DOMNodeList as array in /public_html/dev_host/Jobs.php on line 111

Line 110 - 113:
$productRaw = $data->getElementsByTagName('a');
$productId = $this->parseProductId($productRaw[0]->attributes[0]->nodeValue);
$productAttributes = (array) json_decode($productRaw[0]->attributes[2]->nodeValue);
$productDetails = $this->parseProductDetails($productAttributes['name']);

A: The ability to treat DOMNodeList as an array was added in PHP 5.6.3.
Earlier than PHP 5.6.3, you will have to use $productRaw->item(0); instead of $productRaw[0].
This was bug #67949 and listed in the 5.6.3 changelog, but otherwise appears to be undocumented.


text:
Q: How save only time in Redshift HH:MM:SS Importing table from MySql to RedShift, MySql have to columns which is time datatype
+-----------------+-------------+------+-----+---------+----------------+
| Field           | Type        | Null | Key | Default | Extra          |
+-----------------+-------------+------+-----+---------+----------------+
| id              | int(11)     | NO   | PRI | NULL    | auto_increment |
| typecode        | varchar(20) | NO   |     | NULL    |                |
| slot_start_time | time        | NO   |     | NULL    |                |
| slot_end_time   | time        | NO   |     | NULL    |                |
| parent_id       | int(11)     | NO   |     | NULL    |                |
| createdon       | datetime    | NO   |     | NULL    |                |
| modifiedon      | datetime    | NO   |     | NULL    |                |
+-----------------+-------------+------+-----+---------+----------------+

Redshift doesn't have time data type because of this after importing table slot_start_time, slot_end_time columns return 1970-01-01 in this case slot_start_time, slot_end_time show as Date datatype
When I ALTER both column in Redshift as timestamp then it will return '01/01/70 HH:MM'
So how I can save only time in RedShift.

A: I would strongly suggest against trying out such venture. You might end up using some non-compatible datatype, like string which might actually help you out just to store the time but would be catastrophic when you actually begin to query your data.
In worst case, Redshift might not even populate the date column if it finds the datatype not compatible and the entire column will be populated with null values.
In the Redshift table, store the entire timestamp in the format

yyyy-mm-dd hh:mm:ss (use any placeholder date in the format; as date is irrelevant to you in any case)

and use any of the functions to extract only the timestamp while querying the table (an illustration is shown below).

A: since you don't have time column in Redshift ,you can use the same date , for example '1970-01-01' and then to add the time.
then you will be able to run date_part on the field.
for example
select extract(hour from timestamp '2010-02-16 20:38:40');
date_part


text:
Q: Mongo Java finding Maching record in mongo array My sample doc is
{
    "_id" : ObjectId("51f89c1484ae3aa758ad56e9"),
    "group_name" : "Operator",
    "privileges" : [
        "Add Group",
        "Edit/Delete Group",
        "Add User",
        "Edit/Delete User",
        "Log History",
        "Add Stopwords Group",
        "Edit/Delete Stopwords Group",
        "Add Stopwords",
        "Edit/Delete Stopwords",
        "Recomended Stopwords"
    ],
    "users" : [
        {
            "full_name" : "operator1",
            "user_name" : "operator",
            "password" : "pass$123",
            "status" : "Active"
        },
        {
            "full_name" : "Sumit Dshpande",
            "user_name" : "dsumit",
            "password" : "pass$123",
            "status" : "Active"
        }
    ]
}

I am trying to match user_name and password in users array entered by user.
My java code is :
BasicDBObject query = new BasicDBObject();
List<BasicDBObject> parts = new ArrayList<BasicDBObject>();
parts.add(new BasicDBObject("users.user_name", uname));
parts.add(new BasicDBObject("users.password", password));
query.put("$and", parts);

DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

But it returns all users in matching array.I want users under group so that I can change group privileges.
 Is this right approach for schema designing in nosql.

A: We would need to get holistic information about your application in order to tell you if you're making the right modeling decisions; however, I can help you with your current query.
In order to match multiple attributes within the same element of an array, you should use the $elemMatch operator (http://docs.mongodb.org/manual/reference/projection/elemMatch/).
eg)
collection.find({users:{$elemMatch:{username:uname,password:password}}});


text:
Q: Swift таймер запускается сразу после запуска приложения а не при переходе на другой Экран и как это исправить? Есть два ViewController-a первый это "MenuVC" и второй "ViewController" Первоначальный экран это "MenuVC" к нему же припоял navigatation Controller и на этом view контролере есть кнопка при нажатия на кнопку выполняется переход на "ViewControler" и сдесь хочу чтобы таймер запустился но он запускается сразу же после запуска приложения как исправить ?
Вопрос: Почему таймер запускается сразу после запуска приложения а не при переходе на другой Экран и как это исправить?

вот action перехода при нажатии на кнопки на "MenuVC"
@IBAction func segueAction(_ sender: UIButton) {
    guard let newVC = storyboard?.instantiateViewController(identifier: "ViewController") else { return }

    navigationController?.popToViewController(newVC, animated: true)
}

и вот мой таймер на ViewController
import UIKit

class ViewController: UIViewController {
@IBOutlet var label: UILabel!
var count: Int = 5

var timer: Timer?

override func viewDidLoad() {
    super.viewDidLoad()

    label?.text = "\(count)"
    timerTest()
}

func timerTest() {
    timer = Timer.scheduledTimer(timeInterval: 1,
                      target: self,
                      selector: #selector(justFunc),
                      userInfo: nil,
                                     repeats: count == 0 ? false : true
    )

}
@objc func justFunc(){
    label?.text = "\(count)"

    if count == 0 {
        timer?.invalidate()
        guard let newVC = storyboard?.instantiateViewController(identifier: "MenuVC") else { return }
        navigationController?.popToViewController(newVC, animated: true)
    }

    count -= 1

}

}
у мене обратный таймер после чего заканчивается время хочу сделать переход на первый VC т.е "MenuVC"
 @objc func justFunc(){
    label?.text = "\(count)"

    if count == 0 {
        timer?.invalidate()
        guard let newVC = storyboard?.instantiateViewController(identifier: "MenuVC") else { return }
        navigationController?.popToViewController(newVC, animated: true)
    }

    count -= 1

}

A: Так происходит потому, что при выполнении storyboard?.instantiateViewController(identifier: "ViewController") else { return } происходит вызов viewDidLoad в классе ViewController и таймер запускается до того, как происходит переход и показ контроллера. Можно исправить например так
override func viewDidAppear() {
    super.viewDidAppear()

    label?.text = "\(count)"
    timerTest()
}


text:
Q: Can I create a static library in C++11 and call it from C++03? If I create a C++03-compatible header, and use the same compiler (g++), will this work?

A: In general, yes. Once a module is compiled, the interface tends to be the most important part.
There may be ABI issues, though, depending on whether name mangling or anything like that changed. If you can use it as a shared library, there's a decent chance you can use it statically as well.
More important, however, is standard library versions. Those very likely changed, so passing std objects between the two should be avoided at all costs.


text:
Q: Invalid Identifier on Where Clause PL/SQL Trying to perform a query on data in a table. The query is 'Give album title, album release date and album price of all Neil Young's albums released after 1st January 2015.'
The relevant structure of the table (excluding other parts) is as follows:
create or replace type artist_type as object
(artistName     varchar(50),
 artistRole     varchar(25))
/
create type artist_array_type
as varray(5) of artist_type
/
create or replace type album_type as object
(albumTitle         varchar(50),
 albumPlaytime      number(3), -- minutes
 albumReleaseDate   date,
 albumGenre         varchar(15),
 albumPrice         number(9,2),
 albumTracks        number(2),
 albumArtists       artist_array_type,
 albumReviews       review_table_type,
member function discountPrice return number,
member function containsText (pString1 varchar2, pString2 varchar2) return integer)
not instantiable not final
/

The below is my current query,
select a.albumtitle, a.albumreleasedate, a.albumprice
from albums a
where a.albumartists.artist_type.artistname = 'Neil Young'
    and a.albumreleasedate >= '1-Jan-2015';

however upon attempting to execute it in Oracle SQL Developer I get the error:
ORA-00904: "A"."ALBUMARTISTS"."ARTIST_TYPE"."ARTISTNAME": invalid identifier

*00000 -  "%s: invalid identifier"


text:
Q: Safely execute queries via AJAX on document ready Greeting everybody,
My problem is like this: I have some custom made statistics on my internet site where I log informations on what users do ( google analytics - like ). Obviously I aggregate information a couple of months, but the Tables I store information have grown too large and have a negative impact on page loading. The flow is like this ( in index, so affect all pages ) :
1. Get the included files
2. Execute part of statistics queries
3. Effective page code
4. Execute the last part of statistics queries

To get rid of this problem I want to make those queries on <body onload="execQueries();"> or on document ready with javascript / AJAX.
How can I safely and securely make those queries using AJAX, so that cannot be abused by a client with good knowledge of javascript/ajax. Because if I simply make that JS function it can be accesed everytime by a user with firebug.
The solution I think about is including the use of $_SESSION where I mark in top of my index.php information about those queries ( id, info ) and in the script called by AJAX I check if that $_SESSION['query_info'] is set and I execute it reading all the info from there, and then I use unset($_SESSION['query_info']);. So, if the AJAX is called again, because tat specific $_SESSION['query_info'] does not exists, I do not do anything in my DB.
Do you think this is a secure solution or do you have other ideas? Anything viable is welcomed.
Thank you

A: Try putting your related javascript codes into Closures.


text:
Q: What is the probability that the current will flow in the circuit, if P(1/2, that the bulb will work) and there are 7 bulbs. So, the problem is as follows: Calculate the probability that the current will flow in circuit if the chance that a light bulb will work is 0,5 and there are totally 7 bulbs. Here is the schema:
I don't know whether the location of bulbs affects the independence of the bulbs working. But I only know how to calculate the probability if the bulb working counts as a independent happening. My solution - $P(\text {that all bulbs will work}  )=0,5^{7}=0.0078125$. It is pretty low, because the chance that any bulb won't work is quite high. In fact I know that my answer is incorrect, because the next exercise asks to find the probability that the bulb "c" will work given that current is flowing in circuit. That means, that there is a possibility for a current flowing in circuit even if some bulb is not working? So, I guess there are some bulbs that must be working in order for a current to flow and some that can not work in case some other bulb is working. My guess would be that either a or b has to work but not necessary both of them the c and d must both be working and either e and f must work (am not totally sure about it), then g must work so that current flows. So it would be
$$P=(1-(((1-0,5^2)\cdot 0,5^2)\cdot 0,5^2)\cdot 0,5=0,3984375$$

A: If all bulbs work the current will flow for sure. But this is just a special case. More cases have to be considered.
Note that  the current will flow if and only if
$$(((a\lor b)\land c\land d)\lor e \lor f)\land g$$
where "letter" is true iff the corresponding bulb works.
As regards probabilities,
$$p((a\lor b)\land c\land d)=\left(1-\left(\frac{1}{2}\right)^2\right)\cdot \frac{1}{2}\cdot \frac{1}{2}=\frac{3}{16}.$$
and therefore
$$p(((a\lor b)\land c\land d)\lor e \lor f)=1-\left(1-\frac{3}{16}\right)\cdot \left(1-\frac{1}{2}\right)\cdot \left(1-\frac{1}{2}\right)=1-\frac{13}{64}=\frac{51}{64}.$$
Hence, the required probability is
$$\frac{51}{64}\cdot \frac{1}{2}=\frac{51}{128}\approx 0.398.$$
P.S. In general, for independent events $a$ and $b$,
$$p(a\lor b)=p(a)+p(b)-p(a\land b)=p(a)+p(b)-p(a)p(b)$$
which is the same of $1-(1-p(a))\cdot(1-p(b))$.


text:
Q: What is the definition of being smooth for a function from a Lie group to a Fréchet space? In representation theory of real groups, one is confronted with the notion of smoothness for functions defined on a Lie group with values in a Fréchet space (e.g. see Wallach's Real Reductive Groups I, 1.1.1). What is the precise definition of this? Presumably, the definition should be given in terms of local coordinates, so I am actually asking what smoothness means for a function defined on an open subset of $\mathbb{R}^n$ with values in a Fréchet space $V$. (If $V$ is a Banach space or $n = 1,$ I have no problem.) Proceeding in the usual manner, at some point one has to see $\mathrm{Hom}(\mathbb{R}^n,V)$ as a topological vector space of the same kind as $V$ in order to be able to define the second derivative and so on. On p. 52 of his Representation Theory of Semisimple Groups, Knapp mentions that there exists a canonical topological vector space structure on $\mathrm{Hom}(\mathbb{R}^n,V).$ What is this canonical structure? Does it turn $\mathrm{Hom}(\mathbb{R}^n,V)$ into a topological vector space of the same kind as $V$?

A: For two locally convex topological vector spaces $X,Y$, there are at least two useful topologies on ${\rm Hom}(X,Y)$. The stronger one is given by seminorms $\nu_{x,\mu}(\phi)=\mu(\phi(x))$ as $x$ ranges over $X$ and $\mu$ ranges over seminorms giving the topology on $Y$, and the weaker is given by seminorms $\nu_{x,\lambda}(\phi)=|\lambda \phi(x)|$ where $\lambda$ ranges over the continuous dual of $Y$.
For $X$ LF and $Y$ quasi-complete, either topology is quasi-complete.
For $X$ finite-dimensional, the stronger of these gives ${\rm Hom}(X,Y)$ a topology with features very similar to $Y$. E.g., Frechet for Frechet.

A: Murat Güngör: "... I am actually asking what smoothness means for a function defined on an open subset of $\mathbb R^n$ with values in a Fréchet space ..."
Considering maps $f:E\supseteq U\to F$ where $E,F$ are real locally convex spaces and $U$ is open in $E$, for about a half hundred years there have been many reasonable but generally inequivalent definitions for such a map to be smooth. However, when $E$ and $F$ are Fréchet spaces, all these "reasonable" definitions give the same concept. The Frölicher−Kriegl−Michor approach is among these "reasonable" ones. When $E$ is finite-dimensional, the "reasonable" definition of smoothness is precisely the same as in the case where $F=\mathbb R$. That is, one requires $f$ to posses continuous partial derivatives $\partial^{\kern.6mm\alpha}f$, defined in the classical manner, for all multiindices $\alpha\in\mathbb N_0^{\kern.6mm n}$ where $n$ is the dimension of $E$.

A: Since the above answers and comments refer to the concept of differentiability for functions not just with values IN an infinitely dimensional space, but also defined ON one, despite the fact that your question addresses functions defined on a Lie group and so a finite dimensional space and you explicitly state that this reduce to the case of functions on euclidean space by localisation, let me take the liberty of adding some information on this situation.  This was considered in some detail in the article "Espaces de fonctions différentiables a valeurs vectorielles", Jour. d'Anal. 4 (1954-56) 88-148 by Laurent Schwartz  which is probably still the definitive statement on the subject.  The definition is exactly as in the scalar case using limits of difference quotients.  Schwartz uses the theory of nuclear spaces and tensor products which had just been invented by
Grothendieck for the somewhat analogous case of holomorphic functions and the fact that the smooth functions form a nuclear space makes the theory somewhat simpler.


text:
Q: Time stamp of File in PHP - filemtime() I am trying to get the time stamp using filemtime() of each file and display it on the web page in PHP, I tried much as possible but only getting 1 Jan 1970 as time stamp in return.
Which basically means the timestamp function is not getting the file.
Could you please fix anything wrong in the code.
Thanks
Rahil
foreach($images as $image)
{
    $count+=1;
    if($count==1)
    {
        echo '
';
    }
        /* ATTEMPT ONE*/
        :clearstatcache();
        $path="A2storage/'.$image.'";
        $date = date(filemtime($path));

        echo "Captured at: " . date('h:i A', $date);

        /* ATTEMPT  TWO:*/
        echo date ("H:i:s   | ", filemtime($image));
        print basename($image) ."
";

        echo ' ';

    if($count>=$count_each_column)
    {
        $count=0;
        echo '
';
    }
}

A: There are unwanted single quotes in value of $path
 $path="A2storage/'.$image.'";

Change to
 $path="A2storage/$image";

Also 1st parameter of date function should be format which is missing.
$date = date(filemtime($path));

Change to
$date = filemtime($path);

Then this should print the time
echo "Captured at: " . date('h:i A', $date);


text:
Q: .Net MVC 4 using Windows Authentication - redirect unauthorized user I have an MVC 4 intranet app that I created using Visual Studio 2012. I used WindowsAuthentication and it authenticates users as expected. On some actions I restricted users to certain roles using Authorize attribute. When a user clicks on a link that invokes a controller action for which the user has no authorization it pops up an 'Authentication Required' dialogue. When I login with an account that has no authorization it keeps on popping up the dialogue. Instead I would like this:

*

*When a user is not authorized to access the page, pop up the dialogue as currently doing.

*When the user inputs a login that is valid but not authorized to access the page redirect to another page saying the access is forbidden.

How do I go about doing this? As a relevant information I customized the role provider using the approach discussed here

A: For this you will need a Custom Authorization to handle the unauthorized situations yourself.
You will need a method like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}


text:
Q: changed name servers, but AWS still blocking site I was advised that changing name servers over to a traditional hosting service would be enough to move the site, but it's not working and I think amazon is still controlling something. Is it possible that I need to change more than the name servers?
The A records are pointing to a CloudFront distribution that I have disabled.
The SOA is amazon, not sure what it is.
Two C name records are amazon.
Is something stopping the new nameservers from working?
I have posted an image of the Route 53 records for reference

A: It appears that the delegation has not been updated (through your registrar).
The delegation still looks like this:
rawgymsdublin.com.      172800 IN NS ns-474.awsdns-59.com.
rawgymsdublin.com.      172800 IN NS ns-899.awsdns-48.net.
rawgymsdublin.com.      172800 IN NS ns-1586.awsdns-06.co.uk.
rawgymsdublin.com.      172800 IN NS ns-1276.awsdns-31.org.

This is crucial to change in order to change nameservers, and should not be confused with NS records in your own zone (however, those are expected to match).


text:
Q: Closed form for $\int_0^{\pi/2} \log\bigl( g(x) \bigr) f(n x) \,\mathrm{d}x$ Let $g_+(x) = \sin x$ and $g_-(x) = \cos x$ and similarly let $f_+(x)=\sin x$ be $f_-(x)=\cos x$. I was trying to study the integrals
$$
I_{(\pm,\pm)}(a,n) = \int_0^{\pi/2} \log\bigl( g_{\pm}(ax) \bigr) f_{\pm}(n x) \,\mathrm{d}x
$$
Where $a \in\mathbb{R}$ and $n \in \mathbb{Z}$. Really there is no reason to study $g_\pm(ax)$ since
$$
I_{(\pm,\pm)}(a,n) = \int_0^{\pi/2} \log\bigl( g_{\pm}(ax) \bigr) f_{\pm}(n x) \,\mathrm{d}x = I_{(\pm, \pm)}(1,n) + \log a \int_0^{\pi/2} f_{\pm}(n x)\,\mathrm{d}x
$$
Where the last integral is trivial. To make things easier introduce $I_{\pm,\pm}(1,n) = I_{\pm, \pm}(n)$. By some symmetry arguments it seems one can say that
$$
\begin{align*}
I_{(+,-)}(4n+0) & = I_{(-,-)}(4n+0)  = - \frac{\pi}{8n} \\
I_{(+,+)}(4n+0) & = -I_{(-,+)}(4n+0) = \frac{g}{h} \\
I_{(+,+)}(4n+1) & = I_{(-,-)}(4n+1)  = \frac{1}{4n+1}\log 2 - \frac{t}{w}\\
I_{(+,-)}(4n+1) & = I_{(-,+)}(4n+1)  = \frac{r}{s}\\
I_{(+,-)}(4n+2) & = -I_{(-,-)}(4n+2) = \frac{\pi}{2(4n+2)}\\
I_{(+,+)}(4n+2) & = -I_{(-,+)}(4n+2) = \frac{u}{v}\\
I_{(+,+)}(4n+3) & = -I_{(-,-)}(4n+3) = \frac{1}{4n+3}\log(2) - \frac{p}{q}\\
I_{(+,-)}(4n+3) & = -I_{(-,+)}(4n+3) = \frac{c}{d}\\
\end{align*}
$$
Sorry about the formating, not quite sure how to make it more readable. Seems like there are three cases. 1.) $I_n = (-1)^{2n} \pi/n$, $I_n = q_n/p_n$ and lastly $I_n = \frac{1}{n}\log 2 - \frac{a_n}{b_n}$.
Are there any simple closed forms for $a_n, b_n$ or $q_n, p_n$? I guess the $4n$ and $4n+2$ cases with $\pi/n$ are easy to prove. But I did not quite suceed. Any help or suggestions are welcome =)


text:
Q: Microphone randomly muting since Ubuntu 20.04 I recently upgraded my laptop (Lenovo ideapad 700-15ISK) from Ubuntu 18.04 to 20.04.
Since then, the microphone can randomly switch from activated to muted for no reason, changing its state every second during one or two minutes. It is getting very frustrating because the gnome notification in the middle of the screen is persistent during this lapse of time (switching from activated to muted). It happens at least once a day. Apart from this weird behavior, the microphone works properly.
Reinstalling alsa and pulseaudio didn't fix the issue. Any ideas on this?
Edit
I reinstalled Ubuntu 20.04 wiping everything with it. I'm still having the issue.
A temporary fix (when I'm not using the microphone) is to move the popup notification on the side of the screen with Better OSD extension.

A: After trying out many things, I finally found the solution on another topic.
I needed to had this line to /etc/modprobe.d/alsa-base.conf:
options snd-hda-intel model=alc233-eapd

where "alc233-eapd" is the audio codec reported in kernel.org for my machine.
Use cat /proc/asound/card*/codec* | grep Codec to get your codec and look for the exact name in kernel.org.
Worked like a charm after a reboot!