text:
Q: How do I insert a line break in a String to show on an Android TextView widget? When I set a textView's string manually like below it works.
<TextView
         android:id="@+id/textView1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="line 1 \n line 2"/>

However, when I try to show a String on this textView it doesn't go to a new line.
String sample = "line 1 \n line 2";
textView1.setText(sample);

Note: Actually I am getting the String from a SQLite database. But that shouldn't make a difference right? Beacause it's still a String!
sample = cursor.getString(DBAdapter.COL_sample);
textView1.setText(sample);

So, now my TextView shows "\n" or "\r\n" character instead of a line break.

A: Ah so now since you say it's from the SQLite database, that's the issue there.
You can refer to the answer by Blundell here.
The issue is that SQLite will escape your new line characters so when you retrieve it again, it will come out as \\\n or equivalent in which you will need to unescape to display properly (so remove the extra slash so it is just \n.
So depending on what new line characters are being saved into your database, you will need to handle accordingly.
So using the linked answer, you could do something like this (will depend on the number of backslashes and other characters you need to do):
textView1.setText(sample.replaceAll("\\\\n", "\n"));

If you need to do it in multiple places create a function for this.

A: You can try
sample = sample.replace("\\\n", System.getProperty("line.separator"));

A: It does work when you extract to the strings.xml file (you can quickly do this with the cmd + 1 button).
This is a fix, and you will be properly abstracting your strings as a bonus.


text:
Q: Why do we require nonnegative of monotone increasing theorem in probability? Monotone increasing theorem in probability says if $0\le X_n$ monotone increasing to $X$, then $EX_n$ converges to $EX$.
I know there are counterexamples in the general measure case if we don't have the functions are nonnegative. But I wonder if there is a counterexample in probability measure if we remove this condition.

A: The condition of Monotone Convergence Theorem could be weaken as following: If the sequence of non-decreasing RVs $\{X_n,n\ge 1\}$ satisfies
$$ Y\le X_n\le X_{n+1}, \qquad n\ge n_0, \qquad \text{and}\qquad \mathsf{E}[Y^-]<\infty. \tag{1}$$
Then $\lim\limits_{n\to\infty}\mathsf{E}[X_n]=\mathsf{E}[\lim\limits_{n\to\infty}X_n]$.
On probability space $((0,1), \mathscr{B}_{(0,1)},\mathsf{P}=\lambda)$, let
$$ X_n(x)=-\frac1{nx}, \qquad n\ge 1.$$
then $\lim\limits_{n\to\infty}\uparrow X_n(x)=0$, and $\lim\limits_{n\to\infty}\mathsf{E}[X_n(x)]=-\infty\ne0=\mathsf{E}[\lim\limits_{n\to\infty}X_n(x)]$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I have an offline SQLite database, I want to make it online and work with it In my android studio project, I created an offline SQLite database, that stores data in the user's phone. But right now, I want to make this database online, so everyone who has the app can work with one database (If the first user changes the data, the data will change in second user's application). How I can make my existing database online, so several people can work with it? (Do I need to create a new database using PHP script?)
Here is some of my Database class code:
public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "mylist7641337.db";
public static final String TABLE_NAME = "mylist_data7641337";
public static final String COL1 = "ID";
public static final String COL2 = "NAME1";
public static final String COL3 = "YEAR1";
public static final String COL4= "MONTH1";
public static final String COL5= "DAY1";
public static final String COL6= "PRICE1";
public static final String COL7= "STYEAR1";
public static final String COL8= "STMONTH1";
public static final String COL9= "STDAY1";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, "
            +"NAME1 TEXT, "
            +"YEAR1 INTEGER, "
            +"MONTH1 INTEGER, "
            +"DAY1 INTEGER, "
            +"PRICE1 INTEGER, "
            +"STYEAR1 INTEGER, "
            +"STMONTH1 INTEGER, "
            +"STDAY1 INTEGER)";
    db.execSQL(createTable);
}

A: First of all the default Android database is SQLite. It is an embedded DBMS. SQLite is not a client–server database engine.
TL,DR You cannot provide access to the local database on your device.
The most common way to interact with the backend is to create a REST API/JSON RPC/... and query the backend server for data.
On the backend side, you may have any DBMS you need, but end clients will be abstracted from these details via API.
Of course you can query a database server directly using MySQL, PostgreSQL,... drivers but that is not recommended.
So all in all, you can keep your local data stored in the local database and periodically upload data to the server or you can just interact with the backend without caching data locally. In the latter case, you will be always in-sync.
Hope I explained the matter.


text:
Q: Two fingered swipe v. one fingered drag in iOS In my app I have a UIView derived class Canvas that uses touchesBegan: withEvent:, touchesMoved: withEvent:, and touchesEnded: withEvent: to draw in the canvas. I also want to use a swipe to load the previous (or next) canvas in an array. I tried setting up the following gesture (and a similar one for right):
UISwipeGestureRecognizer* leftSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget: self action: @selector(pageFlipNext)];
leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
leftSwipe.numberOfTouchesRequired = 2;
[_canvas addGestureRecognizer: leftSwipe];
[leftSwipe release];

But my two fingered swipes are still being treated as one-fingered drawing instructions.
How do I get my app to handle the two-fingered swipe correctly?

A: I think that you can use UIPanGestureRecognizer

UIPanGestureRecognizer is a concrete
  subclass of UIGestureRecognizer that
  looks for panning (dragging) gestures.
  The user must be pressing one or more
  fingers on a view while they pan it.

A: First of all, I would get started verifying whether _canvas.multipleTouchEnabled is set to YES. If it isn't, set it to YES.
You might also want to consider
leftSwipe.delaysTouchesBegan = YES;

This will delay the touches to be sent to the _canvas until the gesture fails. You can also use a UIPanGestureRecognizer and do something like this,
[pan requireGestureRecognizerToFail:leftSwipe];


text:
Q: Upload shapefiles to ArcGIS Online using Python script on computer without ArcGIS Pro installation We are trying to automate the upload of shapefiles to ArcGIS Online using a Python script. This script will need to run on a (virtual) computer that does not have an ArcGIS Pro installation. We have a username and password which can be used to log into ArcGIS Online.
We have a Python script which takes four arguments: username, password, url to ArcGIS Online map, and path to the zipped shapefile to be uploaded. This script works when run on a PC with ArcGIS Pro installed, using the Python libraries stored inside the ArcGIS Pro account.
How can we run this script on a PC that does not have ArcGIS Pro? We have tried:

*

*Installing the ArcGIS packages in a Python 3.7 environment set up in Anaconda Navigator, following these instructions: https://support.esri.com/en/technical-article/000022005. This returns a variety of "package conflicts" and does not install the required packages.

*Copying the Python environment folder from the computer with ArcGIS Pro into the Anaconda Navigator envs folder on a computer without ArcGIS Pro. When we run the script using this copied environment, we get the Traceback error "ImportError: Unable to locate a valid Pro or Server installation to use with ArcPy...". Curiously, the shapefile is still uploaded to our account.

Is it possible to run a Python script to upload shapefiles to ArcGIS Online without having an installation of ArcGIS Pro?

A: It seems likely your code requires the ArcGIS Python API. (This is included with ArcGIS Pro's Python). As long as your code does not require anything arcpy, you can migrate your code and workflow to a computer without ArcGIS Pro (thus no Arc* license required). You only need to satisfy the minimum requirements of the ArcGIS Python API. However, if your code calls arcpy, then it's simply impossible to run your script somewhere without either ArcGIS Pro or ArcGIS Server. You cannot just copy the contents of the Python folder on an ArcGIS machine and expect it to work somewhere else. Please abandon this idea, it'll never work properly.
The basic steps you want to follow are in the ArcGIS Python API setup help.
The easiest way is to install Python 3.x+ and Anaconda. You'll note the conda install explanation from the help. Basically, from your Conda command prompt: conda install -c esri arcgis This might be the best path forward for you as you've mentioned you setup Anaconda elsewhere.
If you don't want to use Conda, you can still get all the pieces you need be installing Python 3.x+ (note actual version requirements from the help), and then do a pip install arcgis. This should pull down and install all the Python API requirements at the same time.


text:
Q: how to find factorial of large no I tried to find the factorial of large number ex 1000 by using simple for loop but I didn't get the correct answer whenever I tried I just got 0 as output.
Here is my code
class Factorial
{
    public static void main(String args[])
    {
        int i, fact = 1;
        int number = 1000;
        for (i = 1; i <= number; i++)
        {
            fact = fact * i;
        }
        System.out.println("Factorial of "+number+" is: " + fact);
    }
}

Output:

0

A: For large number use BigInteger in the following way
import java.math.BigInteger;

public class Factorial {
public static void main(String args[]) {

    BigInteger fact=BigInteger.ONE;
    int number = 1000;
    BigInteger bigNum =new BigInteger(Integer.toString(number));
    for(int i=2;i<=number;i++){
        fact = fact.multiply(bigNum);
        bigNum=bigNum.subtract(BigInteger.ONE);
    }
    System.out.println("Factorial of " + number + " is: " + fact);
}
}

Output :
Factorial of 1000 is: 402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

A: Check out these algorithms:
And just rewrite the suitable one in java.


text:
Q: Check if directory has changed I am working on a backup script and I've got a problem. I would like to backup my documents to a ftp server. Because I don't like encfs so I try to realise this by using z-zip and encrypted archives. This is working well but I would like to create a new archive only when a file inside a subdirectory has changed so lftp is only uploading the changed ones.
My codesnippet looks like this:
cd /mnt/HD_a2/documents
for i in */
do 7za a -t7z /mnt/HD_a2/encrypted/ul_doc/"${i%/}.7z" -p1234 -mhe "$i"
done

How can I change this code so it's only creating a new archive when a file inside "i" has been changed within the last 7 days? (This script is executed by cron every 7 days)

A: for i in */
do
    if [ `find "$i" -type f -mtime -7 | wc -l` -gt 0 ]
    then 7za a -t7z /mnt/HD_a2/encrypted/ul_doc/"${i%/}.7z" -p1234 -mhe "$i"
    fi
done

A: So, Barmar`s answer is almost right, but it does not count files correctly. I've looked around for other similar questions  and it seems like it is a common mistake(please note that it is not critical for his solution, but it might confuse other programmers if they touch it, because it does not what most people will expect), no one is accounting the fact that filenames can contain newlines. So here is a bit better version that gives you the right file count:
for i in */
do
    fileCount=$(find "$i" -type f -mtime -8 -exec printf . \;)
    if (( ${#fileCount} > 0 )); then
        7za a -t7z /mnt/HD_a2/encrypted/ul_doc/"${i%/}.7z" -p1234 -mhe "$i"
    fi
done

But what if you have thousands of files? That would build a string that is exactly as long as the number of your files.
So we can use this:
for i in */
do
    fileCount=$(find "$i" -type f -mtime -8 -exec printf . \; | wc -c)
    if (( fileCount > 0 )); then
        7za a -t7z /mnt/HD_a2/encrypted/ul_doc/"${i%/}.7z" -p1234 -mhe "$i"
    fi
done

Or this:
for i in */
do
    fileCount=$(find "$i" -type f -mtime -8 -exec echo \; | wc -l)
    if (( fileCount > 0 )); then
        7za a -t7z /mnt/HD_a2/encrypted/ul_doc/"${i%/}.7z" -p1234 -mhe "$i"
    fi
done

Hoping that useless string data is not going to be cached.
But we only need to know if there is AT LEAST one file, we don't have to count all of them! This way we can stop immediately if something was found.
for i in */
do
    fileFound=$(find "$i" -type f -mtime -8 | head -n 1)
    if [[ $fileFound ]]; then
        7za a -t7z /mnt/HD_a2/encrypted/ul_doc/"${i%/}.7z" -p1234 -mhe "$i"
    fi
done

That's it. This solution will work MUCH faster because it does not have to look for other files and it does not even have to check their mtime. Try running this code without head and you'll notice a significant difference - from several hours to less than a second for my home folder. (I'm not even sure if it will ever manage to finish it on my pc, I have millions of small files in my home folder...)


text:
Q: Edit text within a cell (jquery datatables) Is it possible to edit the text within a cell in datatables. So that when the user double clicks on the cell it becomes editable ?
Thanks

A: Is this what you are looking for?
http://jquery-datatables-editable.googlecode.com/svn/trunk/inline-edit.html
http://code.google.com/p/jquery-datatables-editable/
Hope this helps.

A:

    $(function(){
    $('#mod').click(function(){
    $('#text1').html('<input id="no" size="'+$(this).text().length+'" type="text" value="'+ $('#text1').text() + '">');
    });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="text1"> Text Here </p>
    <input type="button" id="mod" name="modify"  value="modify" />


text:
Q: Mac refusing to change hostname I've been trying to figure out how to use postfix on my Mac and something has gone horribly wrong and I can't seem to fix it.
I believe the problem is related to starting Postfix.
Basically, the Mac seems to refuse to change its hostname. In bash, the user appears as "admin@(null)", if I type 'hostname' I'm given "(null)" also.
Changing the hostname in Sharing from System Preferences causes the second example to change (where it says, for example, "Other users can access shared folders on this computer, and administrators all volumes, at afp://null/ or "lion2".") but the first stays as null.
I've even tried /etc/hostconfig manually setting hostname but nothing works.
Is there somewhere else the hostname is trying to be set but is perhaps corrupt? Or contains an invalid character or something?
This is causing Postfix not to work and report:
postfix: warning: valid_hostname: invalid character 40(decimal): (null)
postfix: fatal: unable to use my own hostname
Please, I really hope someone can help me fix this. I've been trying for hours now.
Cheers,
Scott

A: You should have tried running /bin/hostname directly to set the hostname on the unix/bsd layer, the values from scutil are SystemConfiguration settings which is a higher layer that unix is oblivious to.
It is perfectly normal for sudo scutil --get HostName to return not set even if running /bin/hostname shows you a hostname.
To set the hostname run sudo hostname Foo.bar (this is basically identical to sethostname() BSD call in the code given by another answer)
Optionally you could then run sudo scutil --set HostName Foo.bar to keep the SystemConfiguration settings in sync
NOTE:
The HostName in SystemConfiguration can be different from the LocalHostName and ComputerName , it can also be different from what /bin/hostname returns but it is best that they are all in sync, so you could also do :
sudo scutil --set LocalHostName Foo
sudo scutil --set ComputerName Foo

A: All other answers and help was much appreciated, however after much investigation, the problem appears to lie with my router and iMac: router not allowing the iMac to change its hostname client-side OR possibly sending a weird hostname to the iMac for it to use.

A: Have you tried scutil?
sudo scutil --get pref will show the current value and sudo scutil --set pref name will set the value to name. pref can be one of these:
           ComputerName   The user-friendly name for the system.

           LocalHostName  The local (Bonjour) host name.

           HostName       The name associated with hostname(1) and gethostname(3).

Here's what I get on my machine:
$ sudo scutil --get ComputerName
SteveBook2
$ sudo scutil --get LocalHostName
SteveBook2
$ sudo scutil --get HostName
HostName: not set

A: If you run this tiny program before starting postfix, does it work?
#include <unistd.h>

int main(int argc, char* argv[]) {
    char host[] = "newhostname";
    sethostname(host, sizeof(host));
    return 0;
}

I don't presume to know what else might depend upon your old hostname -- do some testing on all your services after running this.
Details at: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/gethostname.3.html
Update
To compile and run this little program, save its contents to a file (/tmp/newhostname.c will do) then run:
cd /tmp
make newhostname
sudo ./newhostname

At least I assume your make(1) knows how to compile from C sources to runnable binaries with default rules.
If the compiler isn't already installed maybe someone else will have a better idea.


text:
Q: The hight: 100% is not applied and the website shrank. How can I set it to Height: 100% using React + MUI
As you can see that the App bar shrank the webpage side. The Root component is still full 100% and height. The App Bar component is 'App Bar with a primary search field' from https://material-ui.com/components/app-bar/
My code is here.
     <MainWrapper className='App'>

        <div style={{width: '100%', height: '100%'}}>
        <Visible when={isLogged}>
          <Navbar />
        </Visible>
        <Switch>
          <PrivateRouter
            path='/map'
            component={MapPage}
            isLogged={isLogged}
            redirectTo={'/login'}
          />
          <PrivateRouter
            path='/profile'
            component={UserProfile}
            isLogged={isLogged}
            redirectTo={'/login'}
          />
          <PrivateRouter
            path='/login'
            component={Login}
            isLogged={!isLogged}
            redirectTo={'/map'}
          />
          <PrivateRouter
            path='/registration'
            component={Registration}
            isLogged={!isLogged}
            redirectTo={'/map'}
          />
          <PrivateRouter
            path='/'
            component={{}}
            isLogged={false}
            redirectTo={'/login'}
          />
        </Switch>
        </div>
      </MainWrapper>
    );
  }
}

const MainWrapper = styled.div`
  height: 100vh;
  display: flex;
`;

This is Visible Component
export default ({ when, element = null, children }) => when ? children : element;

I've been switching around the page to make it full height. If I get rid of App Bar, then it comes normal. Still could not figure it out :/

A: You can try by removig  <MainWrapper className='App'> like  <MainWrapper> . Because className='App' use react default styles.


text:
Q: FileVersionInfo of output from MSBuild I have written an automated build process, as a .NET 4 application in C#. I am calling MSBuild.exe using System.Diagnostics.Process. The project being built is written in Delphi XE5. I then read the version of the executable that was just built:
version = System.Diagnostics.FileVersionInfo.GetVersionInfo(fileName).FileVersion;

(I can't use the Sytem.Reflection.Assembly class because it's a Delphi app).
If I do this in a Console app, it works great. The version comes back as e.g. "1.2.3.4". But exactly the same code as a Windows service, I get a null string, as if the file had no version info. Same OS credentials in both cases.
Maybe the version info is being cached from when it was being built by MSBuild? But why the difference between console and service? Any ideas how to force reload of version info? I tried FileInfo.Refresh - no difference.
(I know I could use MSBuild programmatically, it just seemed easier to call the exe, without having to implement a logger.)
Update:
I changed it to call MSBuild programmatically, through class Microsoft.Build.Execution.BuildManager, instead of MSBuild.exe. Made no difference.

A: Seems it's not related to MSBuild at all. I think it's a bug in the CLR method, in the way it handles relative paths.
Before the call to GetVersionInfo, the current directory is changed. The path to the file is relative. Looking at the decompiled code for GetVersionInfo, it first checks the file exists:
if (!File.Exists(fileName))
{
  new FileIOPermission(FileIOPermissionAccess.Read, FileVersionInfo.GetFullPathWithAssert(fileName)).Demand();
  throw new FileNotFoundException(fileName);
}

No exception is thrown, so that bit is happy with the relative path.
But by the time fileName gets through to the API methods in Microsoft.Win32.UnsafeNativeMethods, it's not recognised:
int fileVersionInfoSize = Microsoft.Win32.UnsafeNativeMethods.GetFileVersionInfoSize(fileName, out handle);

I converted fileName to a full path, before passing it into GetVersionInfo, and now it works.


text:
Q: Debugging Jersey Unmarshalling Error - Bad Request syntactically incorrect I am building a REST Webservice with the help of Jersey on Glassfish. Now I am struggeling with my custom input Source for my searchQuerys.
If have a search Method:
@POST
@Path("search")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public List<Index> search(SearchQuery searchqry) {
   ...
}

And the Class SearchQuery:
@XmlRootElement
public class SearchQuery implements Serializable {
    private static final long serialVersionUID = 1L;

    public SearchQuery() {
    }

    public SearchQuery(float lat, float lng) {
        this.lat = lat;
        this.lng = lng;
    }

    public float getLat() {
        return lat;
    }

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

    public float getLng() {
        return lng;
    }

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

    private float lat;
    private float lng;
}

And my call:
curl -v -X POST --data-binary "<SearchQuery><lat>3.3</lat><lng>5.4</lng></SearchQuery>" -H "Content-Type: application/xml" -H "Accept: application/xml" http://localhost:8080/WebApplication1/resources/index/search

I tried a restconsole to send the XML request, but I get the same error:

HTTP Status 400 - Bad Requesttype Status
  reportmessageBad Requestdes criptionThe
  request sent by the client was syntactically incorrect (Bad
  Request).GlassFish Server Open Source Edition
  3.1.2* Closing connection #0

I am missing something essentially or can somebody give me a hint how to debug the unmarshalling part inside the Application Server?
I followed the guide at http://xebee.xebia.in/2011/12/30/example-of-restful-webservice-with-xml-and-json-using-maven-jaxb-jersey-tomcat-and-curl/
and tested varius combination of Annotations but no sucess :(

A: FINALLY found the real reason for my problem:
SearchQuery is mapped to "searchQuery" inside XML
TESTClass is mapped to tESTClass inside the XML Entity


text:
Q: Powershell split variable without new line or spaces I'm trying to split the filename without extention and assign it to a new variable. But .split('') function adds new whitespace or tab. Any suggestion to fix this?
$dmpfile = "test.dmp"
$filename = $dmpfile.split('.dmp')
echo $filename
test

ls $filename*.log
no output.............
echo $filename*.log
test     *.log

A: First of all, the split function creates an object with all strings that appear between the split character. You have to access a single item of the property by using $variable[x], where x would be the position of the item you want. In your case you would have to call $filename[0]. (First item is not 1, it starts with 0)
Second, I cannot realy explain why, but if you use the string method split like you did, every single character will be handled as possible delimiter. This is why 'pmdasdfgpmd.dmp'.split(".dmp") will return asdfg - same as if you would use trim. But if you use the function like this:
'pmdasdfgpmd.dmp' -split".dmp"

it will return the filename without extension: pmdasdfgpmd
Third, if you want to remove a part of a string, you can also use the replace method and replace the string by nothing:
either
'test.dmp'.replace(".dmp","")

or
'test.dmp' -replace ".dmp"

But this is just about some basic string replacement in powershell - the easiest way the get the filename without extension is either the way @PetSerAl proposed:
[System.IO.Path]::GetFileNameWithoutExtension($dmpfile)

or you call the Get-Item PSFunction and use the BaseName-Property:
(Get-Item $dmpfile).BaseName

In both cases, the variable $dmpfile must hold the full path to the file, not only the file name.

A: You should use Trim() instead of Split(). $filename = $dmpfile.Trim(".dmp")


text:
Q: Find and replace characters in strings in all .xlsx files in folder VBA I am trying to replace characters such as "/" and "ó", and also a line break (alt + ENTER, manually replaced in excel with find and replace with CTRL + J) in excel files (.xlsx). The characters can be found all over the excel sheets (not one particular range). The reason that I would like to replace these values is that these characters are giving me errors in another application.
I have 20 excel files in one folder, with multiple sheets. I would like to make a script (vba macro) to loop through the excel files and all its sheets and do the replacements.
I am very new with vba/macros.
    Sub ReplaceStringInFile()

    Dim sBuf As String
    Dim sTemp As String
    Dim sFileName As String
    Dim FileExt(2) As String

    ChDir = "C:\mydirectory\"

    FileExt(1) = "xlsx"

    For i = 1 To 1

      sFileName = Dir("*." & FileExt(i))

      Do

        If sFileName = "" Then Exit Do

        sTemp = ""
        Open sFileName For Input As #1
          Do Until EOF(1)
            Line Input #1, sBuf
            sTemp = sTemp & sBuf & vbCrLf
          Loop
        Close #1

        sTemp = Replace(sTemp, "ó", "o")
        sTemp = Replace(sTemp, "/", "")

        Open sFileName For Output As #1
           Print #1, sTemp
        Close #1

        sFileName = Dir()

  Loop

Next i

End Sub

I have tried to combine code from scripts mentioned here:
Find and replace string in all excel files in folder and here
Excel macro to find and replace multiple strings in any text file
Loop through files in a folder using VBA?
But I didn't get it to work.
Help would be very appreciated!


text:
Q: couchdb document update handler single field I want to create a design document which will make the update of a single field (of a document) while it gives back the entire document. In my database, an example of document is the following:
{
    "domain": "google.it",
    "controlled":"0"
}

I'd like to do a query such as:
function(doc) {
    if(doc.controlled=="0") {
       doc['controlled']='1';
       return[doc];
    }
}

I have read CouchDB supports the Document Update Handler but I can't create one. Has someone any guide for beginners?

A: Code below implies doc already exists.
function(doc,req) {
    if (!doc) return [null,"Doc does not exists! Create it first."];
    doc.controlled = doc.controlled=="0"?"1":"0";
    return [doc,"Ok, Updated"]
}

You can use req.query.yourquerystringparameter to update your doc based on request query string parameters
Read official documentation on update functions for details
You find an easy to start guide here
or a more advanced couchdb tutorial here


text:
Q: MS SQL Python Datetime later than but not equal '>' returning result as '>=' I am trying to query a Microsoft SQL database to get all records after the  datetime returned in the previous loop.  I use the '>' operator but the result I am seeing is for '>=' (greater than or equal).
Python (3.6.5 Win10) script:
import pyodbc  # version 4.0.24
import time
import datetime
import json
con = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=mydb;UID=myuid;PWD=mypwd")
cur = con.cursor()
i = 0
lastDatetime = datetime.datetime.strptime('01Jan1970', '%d%b%Y')
while i < 60:
    print("{0}: SELECT * FROM dbo.Data WHERE datetime > '{1}'".format(str(i), lastDatetime))
    cur.execute("SELECT * FROM dbo.Data WHERE datetime > ?", lastDatetime)
    rows = cur.fetchall()
    for k, v in enumerate(rows):
        jsonMsg = json.dumps({
            "transaction_id": v[1],
            "plu": v[2].strip(),
            "qty": int(v[3]),
            "dateTime": str(v[4])
        }, separators=(',', ':'))
        print(str(jsonMsg))
        lastDatetime = v[6]
        print("lastDatetime set to: {0}".format(lastDatetime))
    i = i + 1
    time.sleep(5)

Produces:
0: SELECT * FROM dbo.Data WHERE datetime > '1970-01-01 00:00:00'
{"transaction_id":3201,"plu":"3","qty":1,"dateTime":"2018-08-01 10:45:40.560000"}
lastDatetime set to: 2018-08-01 10:45:40.560000
{"transaction_id":3202,"plu":"5","qty":1,"dateTime":"2018-08-01 10:45:51.563000"}
lastDatetime set to: 2018-08-01 10:48:47.653000
{"transaction_id":3230,"plu":"8","qty":2,"dateTime":"2018-08-01 10:48:47.653000"}
lastDatetime set to: 2018-08-01 10:48:47.653000
1: SELECT * FROM dbo.Data WHERE datetime > '2018-08-01 10:48:47.653000'
{"transaction_id":3230,"plu":"8","qty":2,"dateTime":"2018-08-01 10:48:47.653000"}
lastDatetime set to: 2018-08-01 10:48:47.653000
2: SELECT * FROM dbo.Data WHERE datetime > '2018-08-01 10:48:47.653000'
{"transaction_id":3230,"plu":"8","qty":2,"dateTime":"2018-08-01 10:48:47.653000"}
lastDatetime set to: 2018-08-01 10:48:47.653000

I run the query in SQL Server Management Studio and I get the expected result:
SELECT * FROM dbo.Data WHERE datetime > '2018-08-01 10:48:47.653'

returns no records.
What am I missing or what should I change in the python script to get the expected result?
Thanks.
EDITS:
Add the '' to the print of the sql string around the datatime. Didn't make a difference to the result.

A: You are hitting the breaking change for SQL 2016+ noted here:

Under database compatibility level 130, implicit conversions from
  datetime to datetime2 data types show improved accuracy by accounting
  for the fractional milliseconds, resulting in different converted
  values. Use explicit casting to datetime2 datatype whenever a mixed
  comparison scenario between datetime and datetime2 datatypes exists.
  For more information, refer to this Microsoft Support Article.

Breaking Changes in SQL Server 2016
The problem is that your table is still using the old datetime data type.  And it's a really weird type.  It doesn't have ms resolution.  Its resolution is actually 1/300th of a second.  So the actual stored value is not always quite what it looks like. The storage is inexact, like for floating point numbers.
The new better datetime2 has more precision and always stores decimal fractional seconds.  Anyway SQL 2016 changed how datetime gets converted to datetime2, which has a side-effect of making comparisons involving implicit conversions sometimes break.
To fix this either change the data type on your table to datetime2(3) for 1ms precision.  Or force the parameter to be a datetime, instead of a datetime2.  I don't know if pyodbc allows that, but you can force the conversion in the query easily:
cur.execute("SELECT * FROM dbo.Data WHERE datetime >= cast(? as datetime)", lastDatetime)

Now instead of converting the table column to datetime2 you convert the parameter value to datetime, and the comparison works as expected.
Or reduce your database compatibility level to 120.

A: I've solved it by adding 1 millisecond to the last time along with change the '>' to a '>='. As the millisecond is the smallest increment on time in MS SQL at the moment, this method should not miss any data.
I suspect it has something to do with pythons handling of floats but cannot be sure as adding 1msec as a float to the seconds part didn't quite increment it enough.
Revised code:
import pyodbc  # version 4.0.24
import time
import datetime
import json
con = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=mydb;UID=myuid;PWD=mypwd")
cur = con.cursor()
i = 0
lastDatetime = datetime.datetime.strptime('01Jan1970', '%d%b%Y')
while i < 60:
    print("{0}: SELECT * FROM dbo.Data WHERE datetime >= '{1}'".format(str(i), lastDatetime))
    cur.execute("SELECT * FROM dbo.Data WHERE datetime >= ?", lastDatetime)
    rows = cur.fetchall()
    for k, v in enumerate(rows):
        jsonMsg = json.dumps({
            "transaction_id": v[1],
            "plu": v[2].strip(),
            "qty": int(v[3]),
            "dateTime": str(v[4])
        }, separators=(',', ':'))
        print(str(jsonMsg))
        lastDatetime = v[6]
        # work around a bug with datetime > returning as if >=
        lastDatetime = lastDatetime + datetime.timedelta(milliseconds=1)
        print("lastDatetime set to: {0}".format(lastDatetime))
    i = i + 1
    time.sleep(5)


text:
Q: Why do we have instructions such as RDRAND instead of an I/O which would gives us similar results? I'm wondering what was the reason behind designing a CPU specific instruction to generate random numbers?
The Intel processor has RDRAND and RDSEED. The PPC also has an equivalent instruction.
Wouldn't it make more sense to have a separate chip and just do some I/O to get those numbers? It seems to me that it makes the CPU even more complex for a very specialized instruction (most software never use random numbers!) when I/O has been around for ages and should work just fine.

A: We have both.
The TPM can generates crypto-secure random numbers (after all, it's a "crypto-chip") and the TPM is present on many, if not all, Intel based motherboards since Haswell.
Proprietary CSRNG PCI(e) cards are commercially available too.
I once attended a presentation of an home-made CSRNG with Arduino.
 That guy had no notion of statistics or algebra. To be honest, the whole presentation was pathetic.
You can't just make a chip and claim it is a CSRNG, you must gain certifications, there are standards and methods.
Getting those certifications is expensive and hard.
Furthermore, to handle a wide bandwidth you also need a fast (u)-processor.
One of the goal of the TPM commitee was to make it cheap, the end result was that TPM chips are slow.
If you add the, relatively, low market demand for such chips we can clearly see that CSRNG chip are indeed expensive.
External devices are also prone to physical attacks, the chip can be easily desoldered/decapped or the bus tapped or replaced.
This is true even for the CSRNG inside the CPU, attacks are known, one reduce its entropy by altering its transistors.
However that requires a whole different kind of tools.
PCI(e) CSRNGs will probably use DMA to transfer a required number of bytes of entropy, that requires some coordination interface with the OS to known, for example, when a transfer is in progress.
And, of course, the payload would be in memory and that means a bigger software surface attack and an extra step to get it in the registers.
Accessing the memory is in the order of ~200-300 cycles.
Using port-mapped IO (i.e. the in instruction) will bring the payload directly in a register, but only 32-bit at a time and it's no faster than an ordinary load.
RDRAND is an user-mode instruction, allowing user-mode applications access to a CSRNG without any extra burden but to check for its support.
It comes with almost all of the recent CPUs, it almost feels like it's free.
Finally, there is a marketing aspect playing.
If your manufacturing process has improved and has given you a few [insert-a-reasonable-length-unit-here] squared of space in the die, you can improve the micro-architecture or add a new feature.
The former is hard, the latter is relatively easy to design and it may give you a boost over your competitors: common tools run faster on your CPU and that just because you could afford more space in the die.

A: It is an explicit design decision in RdRand and RdSeed that it delivers its random number into the target register of the program executing the instruction, bypassing the OS, libraries, hypervisors, device drivers and anything else that may present an increased attack surface.
Having the RNG on die was (a) the obvious thing to do since it's only a tiny sliver of the whole die and (b) the right thing from a security point of view, preventing simple probing of the path from the RNG to the running code.


text:
Q: Log4Net programmatically check IsEnabledFor for Appender filters How do I programmatically check that IsEnabledFor is true for a certain appender filter.
This is my config:
<log4net>
 <root>
  <level value="ALL" />
  <appender-ref ref="appender" />
 </root>

 <appender name="appender" type="log4net.Appender.FileAppender">
  <filter type="log4net.Filter.LevelRangeFilter">
   <levelMin value="ERROR" />
   <levelMax value="FATAL" />
  </filter>
 </appender>

<log4net>

Ok so if I set <root> Level to say ERROR and I do a IsEnabledFor(Debug) it returns true but if I set <root> level to ALL and add filters to the appender its not taking into account the filters.
How do I get it to include appender filters or is there another way to query this ?

A: I could be wrong, but I do not see how this can be done easily. What you could do is something like this:
var hierarchy = LogManager.GetRepository() as Hierarchy;
if(hierarchy != null)
{
    var appenders = hierarchy.GetAppenders();
    foreach( IAppender appender in appenders)
    {
        var appenderSkeleton = a as AppenderSkeleton
        if (appenderSkeleton != null)
        {
            IFilter filterHead = appenderSkeleton.FilterHead;
            // now analyse the filter chain
        }
    }
}

I did not test this code, but it should work more or less. What you get this way is the head of any configured filter chain for all appenders that derive from AppenderSkeleton. The head of the filter chain implements IFilter (as do all filters) and it contains one method and a property:
FilterDecision Decide(LoggingEvent loggingEvent);
IFilter Next { get; set; }

Now you could create an instance of a LoggingEvent with the log level you are interested in, and go through the filter chain by using the Next property and test each filter by calling FilterDecision.
This tells you if the appender would accept or deny the logging event, but you need to be aware that an appender might also filter based on other criteria (e.g. message content) and thus it would not exactly be an "IsEnabledFor" implementation.

A: I know this is an old post, but Stefan's answer helped be construct the following. My use case was a custom Logging Level for Performance of a given operations. Obviously we required the ability to toggle this level.
In my particular case we are only using the LevelMatchFilter so we wouldn't run into the issues you would with the other filter types...
    /// <summary>
    /// evaulates if a custom log level is enabled.
    /// </summary>
    /// <param name="log"></param>
    /// <param name="level"></param>
    /// <returns></returns>
    public static bool IsLevelEnabled(this log4net.ILog log, log4net.Core.Level level)
    {
        var hierarchy = log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy;
        if (hierarchy != null)
        {
            var appenders = hierarchy.GetAppenders();
            foreach (log4net.Appender.IAppender appender in appenders)
            {
                var appenderSkeleton = appender as log4net.Appender.AppenderSkeleton;
                if (appenderSkeleton != null)
                {
                    log4net.Filter.IFilter filterHead = appenderSkeleton.FilterHead;
                    //traverse the filter chain
                    var currentFilter = filterHead;
                    while (currentFilter.Next != null)
                    {
                        if (currentFilter is log4net.Filter.LevelMatchFilter)
                        {
                            //if the filter level matches the target
                            if (((log4net.Filter.LevelMatchFilter)currentFilter).LevelToMatch == level)
                            {
                                return true;
                            }
                        }
                        //move to the next filter
                        currentFilter = currentFilter.Next;
                    }
                }
            }
        }
        return false;
    }


text:
Q: Data from serverside not display hello guys i try data use datatables from serverside (SQL Server) if me use code
my data not found or not availaible. this is my code
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."   LIMIT ".$requestData['start']." ,".$requestData['length']."   ";

please help me

A: Use OFFSET and FETCH in SQL Server OFFSET FETCH Clause.
SELECT * FROM table ORDER BY column OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;

Possible duplicate: LIMIT 10..20 in SQL Server.


text:
Q: Scroll height adjustment with infinity scroll At the moment when 'scroll' is at the very bottom, the function getUsers () is called. How to set the scroll so that it doesn't reach the end of the slider, and the getUsers () function is called. That there would be an infinity scroll effect. I mean the scroll effect like here: https://codesandbox.io/s/ww7npwxokk. When the scroll reaches the bottom, it goes back.
Code here: https://stackblitz.com/edit/react-nq8btq
import './style.css';
import axios from 'axios';

class App extends Component {
  constructor() {
    super();
    this.state = {
      users: [],
      page: 1
    };
  }

  componentDidMount() {
    this.getUsers();
  }

  getUsers = () => {
    axios({
      url: `https://jsonplaceholder.typicode.com/users`,
      method: "GET"
    })
    .then(res => {
      this.setState({
        users: res.data
      });
    })
    .catch(error => {
      console.log(error);
    })
  }

  scroll = (e) => {
    const page = this.state.page;
    const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
    if (bottom) {
      alert('bottom');
      this.getUsers()

      this.setState({
        page: this.state.page + 1
      })
    }

    const top = e.target.scrollTop;

     if(top === 0 && page > 1) {
        alert('I AM AT THE TOP');

         this.setState({
          page: this.state.page - 1
        })
      }
  }

  render() {
    console.log(this.state.page)
     console.log(this.state.users)
    return (

              {this.state.users.map((user, index) =>

                  {user.name}

              )}

    );
  }
}

render(<App />, document.getElementById('root'));

A: Here I've updated your code, slightly simplified, but mostly your code with the key points commented.
class App extends Component {
  state = {
    users: [],
    page: 1
  };

  componentDidMount() {
    this.getUsers();
  }

  getUsers = () => {
    axios({
      url: `https://jsonplaceholder.typicode.com/users`,
      method: "GET"
    })
    .then(res => {
      this.setState({
        // *you must append to users in state, otherwise
        // the list will not grow as the user scrolls
        users: [...this.state.users, ...res.data],
        page: this.state.page + 1
      });
    })
    .catch(error => {
      console.log(error);
    })
  }

  scroll = (e) => {
    // *simplified, to only handle appending to the list
    // note the 50px from the bottom, adjust as required
    // so that the request is made before the users reaches
    // the bottom of the page under normal scrolling conditions.
    if (e.target.scrollHeight - e.target.scrollTop <= e.target.clientHeight + 50) {
      this.getUsers();
    }
  }

  render() {
    return (

          {this.state.users.map((user, index) =>
            // *always add a unique key for each item

              {user.name}

          )}

    );
  }
}

A: All you need to do is decide when to call get users.
i.e. if you want it to be called when you have already scrolled through 70% the height then the factor would be 0.3 (30%)
Whenever the scroll exceeds the 70% mark this.getusers() would be called.
Check out how I have modified the same condition written by you.
Rest of the code remains the same
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import axios from 'axios';

class App extends Component {
  constructor() {
    super();
    this.state = {
      users: [],
      page: 1
    };
  }

  componentDidMount() {
    this.getUsers();
  }

  getUsers = () => {
    axios({
      url: `https://jsonplaceholder.typicode.com/users`,
      method: "GET"
    })
    .then(res => {
      this.setState({
        users: res.data
      });
    })
    .catch(error => {
      console.log(error);
    })
  }

  scroll = (e) => {
    const page = this.state.page;
    const bottom = e.target.scrollHeight - e.target.scrollTop < e.target.clientHeight-0.3*e.target.clientHeight;
    if (bottom) {
      alert('bottom');
      this.getUsers()

      this.setState({
        page: this.state.page + 1
      })
    }

    const top = e.target.scrollTop;

     if(top === 0 && page > 1) {
        alert('I AM AT THE TOP');

         this.setState({
          page: this.state.page - 1
        })
      }
  }

  render() {
    console.log(this.state.page)
     console.log(this.state.users)
    return (

              {this.state.users.map((user, index) =>

                  {user.name}

              )}

    );
  }
}

render(<App />, document.getElementById('root'));

A: This lib should do the trick for you
$ yarn add react-infinite-scroller

Very simple to implement
<InfiniteScroll
  pageStart={0}
  loadMore={this.getUsers()}
  hasMore={this.state.hasMoreUsers}
  loader={
loading ...
}
>

    {user.name}

</InfiniteScroll>

Don't forget to import the lib in your component file
import InfiniteScroll from 'react-infinite-scroller';


text:
Q: How to decrypt PKCS#7 enveloped data with Azure Key Vault I have certificates with private keys installed in Azure Key Vault, and I need to decrypt mime-content of type 'application/pkcs7-mime; smime-type=enveloped-data' (Cryptographic Message Syntax)
Can this be done with Azure Key Vault and C#/.NET?
Seems to me that Decrypt only works with raw data against the KeyVault client.
Is there some easy way to unwrap the mime content and decrypt bytes, manually?


text:
Q: Patience satisfied I'm looking for a word which describes the resolution of patience.
Example 1: If someone is waiting (being patient) in a room for his/her name to be called and it finally happens.
This also might include the act of running out of patience
Example 2: If someone is waiting (being patient) in a room for his/her name to be called and the office closes before the patient is called and the patient is forced to leave.
What is that resolution or action called?

A: You've waited almost 5 minutes for an answer to this question, and now your patience has been rewarded.

A: Assuagement Freedom, especially from pain: alleviation, ease, mitigation, palliation, relief.


text:
Q: Changing the keys of an array Say I have these :
$services = array();
$services["services0"];
$services["services1"];
$services["services2"];
$services["services3"];

And I would like to create some kind of loop to change these to:
$services[0];
$services[1];
$services[2];
$services[3];

How would you go about doing so? Not knowing how many key : value pair you have in an array?

A: The easiest way to do this and discard the original keys is to just run the array through array_values():
$new_array = array_values( $old_array);

You can see from this demo that the following example:
$services = array();
$services["services0"] = 's0';
$services["services1"] = 's1';
$services["services2"] = 's2';
$services["services3"] = 's3';

$services = array_values( $services);

print_r( $services);

Produces this array:
Array
(
    [0] => s0
    [1] => s1
    [2] => s2
    [3] => s3
)

A: Try something like the following code:
$dummy_array = $services;
$services = array();
foreach($dummy_array as $service) {
    $services[] = $service;

}

What is happening here is that you are unsetting services (but saving it first) Then you loop through your saved version adding the values back into an array. The line $services[] = $service; is key here. This appends a value to the end of an existing array with a standard key. ie 0, 1, 2, 3 and so on. This creates the result that you want of removing the string keys and replacing them with standard array key indecies. Try it out and see what you get. Good luck


text:
Q: ASP.Net architecture for passing upload to third party I'm working on an application which is designed to stand on top of the YouTube API and pass uploads from the user to the YouTube.Videos.Insert endpoint (using the .NET client library they provide). Right now, my application is built as a simple ASP.NET MVC application, but I'm quickly realizing that may not be the best approach, because the issue quickly crops up that the upload process could be a rather long-running one.
What would the best-practice architecture be in order to do this effectively? My ideas thus far are:

*

*Some sort of queue strategy, where the MVC app puts the upload on the queue, and a background process pops it off and performs the further upload to YouTube. This seems inefficient, though, since it adds storing the file temporarily and retrieving it again for processing to the overall overhead of the application.

*A separate microservice API with an endpoint for receiving the actual upload, which I would contact via Javascript from the front-end of my app; it would receive the file, return a 202 Accepted, and pass the upload stream off into an async thread and process it immediately. This seems more efficient but I'm worried about scalability if anyone besides me ends up using this thing.

I would love additional architecture insight on the best way to approach this.

A: I would approach this with a separate service API. The task of uploading many potentially large files is a long-running process that you don't want touching your web app. The main advantage to this approach is that if something goes wrong, it does not affect your web application. If an upload fails, you don't want to restart your web application to account for that.
Since you are worried about scalability regarding this approach, I would consider using a background task manager, which is perfect for these sort of fire-and-forget tasks. Personally, I use and recommend Hangfire, as it comes with a beautiful integrated dashboard that lets you observe your tasks as they run. It also allows you to automatically retry on failure (configurable), and I think overall it suits your needs well.
I use it for a similar situation wherein I need to establish multiple websocket connections, and re-establish one if it were to fail. I have a small program that adds services to my Hangfire queue via arguments.
Other options include Quartz.Net and FluentScheduler, but unfortunately I am not nearly as familiar with them.


text:
Q: Can I anywhere get packages of ancient Ubuntu versions? https://packages.ubuntu.com/ provides a list of packages of all versions of Ubuntu from Trusty.
There is also http://old-releases.ubuntu.com/ ; however, while I can download ancient Ubuntu versions from there, can I also download packages for those ancient versions?
I don't really need the packages themselves; all I need is a list of package names (preferably properly categorized).


text:
Q: FreeBSD slow transfers - RFC 1323 scaling issue? I think I may be having an issue with window scaling (RFC 1323) and am hoping that someone can enlighten me on what's going on.

*

*Server: FreeBSD 9, apache22, serving a static 100MB zip file. 192.168.18.30

*Client: Mac OS X 10.6, Firefox 192.168.17.47

*Network: Only a switch between them - the subnet is 192.168.16/22 (In this test, I also have dummynet filtering simulating an 80ms ping time on all IP traffic. I've seen nearly identical traces with a "real" setup, with real internet traffic/latency also)

Questions:

*

*Does this look normal?

*Is packet #2 specifying a window size of 65535 and a scale of 512?

*Is packet #5 then shrinking the window size so it can use the 512 scale and still keep the overall calculated window size near 64K?

*Why is the window scale so high?

Here are the first 6 packets from wireshark. For packets 5 and 6 I've included the details showing the window size and scaling factor being used for the data transfer.
No. Time Source Destination Protocol Length Info

108 6.699922 192.168.17.47 192.168.18.30 TCP 78 49190 > http [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=8 TSval=945617489 TSecr=0 SACK_PERM=1

115 6.781971 192.168.18.30 192.168.17.47 TCP 74 http > 49190 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1460 WS=512 SACK_PERM=1 TSval=2617517338 TSecr=945617489

116 6.782218 192.168.17.47 192.168.18.30 TCP 66 49190 > http [ACK] Seq=1 Ack=1 Win=524280 Len=0 TSval=945617490 TSecr=2617517338

117 6.782220 192.168.17.47 192.168.18.30 HTTP 490 GET /utils/speedtest/large.file.zip HTTP/1.1

118 6.867070 192.168.18.30 192.168.17.47 TCP 375 [TCP segment of a reassembled PDU]

Details:
Transmission Control Protocol, Src Port: http (80), Dst Port: 49190 (49190), Seq: 1, Ack: 425, Len: 309
Source port: http (80)
Destination port: 49190 (49190)
[Stream index: 4]
Sequence number: 1 (relative sequence number)
[Next sequence number: 310 (relative sequence number)]
Acknowledgement number: 425 (relative ack number)
Header length: 32 bytes
Flags: 0x018 (PSH, ACK)
Window size value: 130
[Calculated window size: 66560]
[Window size scaling factor: 512]
Checksum: 0xd182 [validation disabled]
Options: (12 bytes)
No-Operation (NOP)
No-Operation (NOP)
Timestamps: TSval 2617517423, TSecr 945617490
[SEQ/ACK analysis]
TCP segment data (309 bytes)

A: 1.)  512 isn't really a high window scale - it's just saying to shift the offered window size to the left by 9 bits.   Setting the window size to 130 (otherwise a very, very low value) and then applying a scale factor of 512 gets you to 66560 (130<<9).
2.) 100M is likely too small a file.  The fact that the scale has been negotiated at all suggests that things are working OK.  Try a larger file to better observe the behavior.  If nothing else you'll get a better sense of the real throughput.
3.) Also bear in mind that the behavior of particular clients can actually specifically override the behavior of the OS - the built in FTP client in Solaris, for example, used to limit window size to 64K regardless of how the OS was configured.

A: I got word from the sysadmin team that this issue was being caused by some issue with the VMWare net driver not respecting / playing nice the sysctl tunables. Throughput with the same setup on physical hardware has throughput with a reasonable percentage for the pipe rather than the 1/10th or less we saw with VMware.


text:
Q: Ошибка KeyError в функции drop df.columns
>>> Index(['RowNumber', 'CustomerId', 'Surname', 'CreditScore', 'Geography',
       'Gender', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard',
       'IsActiveMember', 'EstimatedSalary', 'Exited'],
      dtype='object')

df = df.drop(['RowNumber', 'CustomerId', 'Surname', 'CreditScore'], axis=1, inplace=True)
df>>>KeyError: "['RowNumber' 'CustomerId' 'Surname' 'CreditScore'] not found in axis"

A: если вы используете параметр inplace=True, то замена происходит в самом фрейме и функция возвращает None:
In [96]: df = pd.read_csv(r"/tmp/Churn_Modelling.csv")

In [97]: df.columns
Out[97]:
Index(['RowNumber', 'CustomerId', 'Surname', 'CreditScore', 'Geography',
       'Gender', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard',
       'IsActiveMember', 'EstimatedSalary', 'Exited'],
      dtype='object')

In [98]: df.drop(['RowNumber', 'CustomerId', 'Surname', 'CreditScore'], axis=1, inplace=True)

In [99]: df.columns
Out[99]:
Index(['Geography', 'Gender', 'Age', 'Tenure', 'Balance', 'NumOfProducts',
       'HasCrCard', 'IsActiveMember', 'EstimatedSalary', 'Exited'],
      dtype='object')

поэтому надо делать либо так:
df.drop(['RowNumber', 'CustomerId', 'Surname', 'CreditScore'], axis=1, inplace=True)

либо так:
df = df.drop(['RowNumber', 'CustomerId', 'Surname', 'CreditScore'], axis=1)

лично я предпочитаю более явный стиль:
df = df.drop(columns=['RowNumber', 'CustomerId', 'Surname', 'CreditScore'])


text:
Q: Facebook permissions to know if a friend uses the same app I can successfully grab a list of friends with this NSURL, using the permissions "publish_stream":
NSURL *friendsList = [NSURL URLWithString:@"https://graph.facebook.com/me/friends

However, when I try the same thing with an added field, as in this URL:
NSURL *friendsList = [NSURL URLWithString:@"https://graph.facebook.com/me/friends?fields=installed"];

I get an error:
error =     {
        code = 2500;
        message = "An active access token must be used to query information about the current user.";
        type = OAuthException;
    };

So my question is what permissions should I be asking for to make the second URL work?
Bonus question: What URL param do I include to get a small profile pic come back in the same JSON object?
Thanks :)

A: According to the docs, you it Requires app access_token. However, playing with Graph API Explorer, I could get this info without this permission.
You can take a look at Graph API Explorer to test.
Also, the query on the above link returns the picture field, which will have an URL with the user picture.


text:
Q: Executing code in bracket with function? I'm trying to create a wrapper function for system.scheduler.schedule. I started by writing the following code:
def every(time : Int) : Unit = {

    val system = ActorSystem("timer")
    import system.dispatcher
    val tickActor = system.actorOf(Props(classOf[TickActor], this))

    system.scheduler.schedule(0 milliseconds, time.milliseconds, tickActor, Tick)
}

I'm trying to use it like this:
timer.every(10) {
    println("HI")
}

However, I'm getting: Unit does not take parameters
I don't think I've set my function call up correctly to accept the { }, but I don't know how. I don't even know the terminology so I can look it up... I'm really knew to scala.
What do they call something like this and what do I need to do to fix it?


text:
Q: Create texture without TexImage2D Is this possible to create an OpenGL texture without sending an array of pixel data to the driver, and using glVertex or similar?
Node-x11 GLX implementation lacks TexImage2D function, so I am trying to find the way aroundto create a texture.


text:
Q: how to display the rate at which requests are being received over a certain time interval in grafana right now this widget reports the number of responses given by the the API as a cumulative amount. Because of this, differences in the rate is not immediately clear. How to change the graph to display the rate? eg: at 10am-4pm the request I got is 1000, 4pm-10pm is 500, it go up and down, not cumulative.
This is right now

This is Prometheus endpoints:
# HELP get_tax_requests_seconds Response latency(seconds) of gRPC.
# TYPE get_tax_requests_seconds histogram
get_tax_requests_seconds{m_application="adapter-mvp",method = "GetData", m_env="test",quantile="0.5",} 0.0

After I add rate, it shows like this, not the number of request

A: Use the rate function, like in the following example:
sum(rate(get_tax_requests_seconds_count{<labels>}[1h])) * 60 * 60


text:
Q: SELECT .. JOIN para relacionar 2 tablas Buenas noches, tengo un problema ya que actualmente poseo dos tablas en mysql y al momento de realizar la consulta no puedo hacer que estas me muestren todos sus datos ya que no se como relacionarlas. Las claves primarias son CedulaAlumno y CedulaRepresentante, que ocurre con esto? que los datos nunca serán iguales y por ende no se como asociarlos para obtener los resultados. Aquí dejo el código y las pantallas de la base de datos. Muchas gracias.
PD:Como veran no se donde debo colocar el inner join si es que debo colocarlo.
Tabla alumnos

Tabla representantes

A continuación el código que tengo hasta el momento:
<!DOCTYPE html>

    <title>Consulta de Registros</title>

<?php

$Conexion = mysqli_connect("localhost", "root", "", "tesis") or die ("Problemas con la conexion");

$Registros = mysqli_query($Conexion, "select TipoCedulaAlumno, CedulaAlumno, PrimerApellidoAlumno, SegundoApellidoAlumno, PrimerNombreAlumno, SegundoNombreAlumno, FechaNacimientoAlumno, NacionalidadAlumno, EdadAlumno, SexoAlumno, DireccionAlumno, TelefonoAlumno, CorreoAlumno from alumnos where CedulaAlumno = '$_REQUEST[CedulaAlumno]'") or die ("Problemas en el select: ".mysqli_error($Conexion));

if ($Reg = mysqli_fetch_array($Registros))

{
    echo "Cedula del Alumno: ".$Reg['TipoCedulaAlumno']." ".$Reg['CedulaAlumno']."
";
    echo "Apellidos del Alumno: ".$Reg['PrimerApellidoAlumno']." ".$Reg['SegundoApellidoAlumno']."
";
    echo "Nombres del Alumno: ".$Reg['PrimerNombreAlumno']." ".$Reg['SegundoNombreAlumno']."
";
    echo "Fecha de Nacimiento del Alumno: ".$Reg['FechaNacimientoAlumno']."
";
    echo "Nacionalidad del Alumno: ".$Reg['NacionalidadAlumno']."
";
    echo "Edad del Alumno: ".$Reg['EdadAlumno']."
";
    echo "Sexo del Alumno: ".$Reg['SexoAlumno']."
";
    echo "Direccion del Alumno: ".$Reg['DireccionAlumno']."
";
    echo "Telefono del Alumno: ".$Reg['TelefonoAlumno']."
";
    echo "Correo del Alumno: ".$Reg['CorreoAlumno']."
";

}

else

{
 echo "No se encontro un alumno con esa Cedula";
}
 ?>

A: Suponiendo que el campo cedulaAlumnoRepresentante de la tabla representates és FK hace referencia a la clave primaria de la tabla alumno al que representa.
Para ver todos los datos del alumno + todos los datos del representante (en caso que lo haya) debes usar esta SELECT:
SELECT * FROM alumnos LEFT JOIN representantes
ON alumnos.CedulaAlumno = representantes.cedulaAlumnoRepresentante

A: Creo que estas malinterpretando las cosas, pues mira, a lo que veo las 2 tablas tienen una relación a lo que es persona, osea... son personas!..
Pues lo que yo haría es lo siguiente, me crearía una tabla llamada PERSONA, donde contendría lo simple: id_persona, Nombre, Apellido, año_nacimiento, etc.
Luego crearía otra tabla ALUMNO, donde contendría sus propios campos: id_alumno,fk_carrera,fk_id_persona(este es el id de la persona),fk_representante(aquí estará un ID de PERSONA)
SI necesitas mas ayuda, puedo asesorarte via skype: desarrollador_01


text:
Q: How to indentify which user profile is activated on Android Multi User feature? Android has Multi Users feature:

I'd like to identify on my application on some part of the code which is the actual activated user. For example if the activated user is the First, Second or Guest.
Is there any way to check that?

A: I had just found a way to identify the Main user (system user) the first one that was created on system.
UserManager um = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
um.isSystemUser();

With that I can identify if the user is different of the system user.


text:
Q: Clone GitHub repository in VSCode I'm trying to clone a GitHub repository into the newest release of VSCode (1.3.0). Can this be done natively or do I need to add an extension or additional binary?
I've also searched for a blog article and coming up empty handed so any guidance would be appreciated
Paul

A: Starting from the 1.8 (November) update of vscode you can now clone your Git repository from within the vscode.
You can execute it from the Command Palette. Press F1 (or ⇧+⌘+P on Mac) and search for Git: Clone. Confirm the command and paste the repository url.

A: There are now two programmatic ways how to clone a repository. VS Code handles the vscode:// protocol now, so you could clone a repository by clicking on a link somewhere on a web page
For example, clicking on the following link invokes VS Code, lets you select a folder on your disk, fetches the code and finally suggests to open that location as a workspace.
vscode://vscode.git/clone?url=https%3A%2F%2Fgithub.com%2Fmicrosoft%2Fvscode-extension-samples
Alternatively, if you are trying to trigger the cloning from an extension code, use the built-in VS Code command git.clone with the repo url as the only argument.
import { commands} from 'vscode';

commands.executeCommand("git.clone", "https://github.com/microsoft/vscode-extension-samples");

Both seem to do the same as the Git: Clone command mentioned by Jakub.

A: Even faster, with VSCode 1.58 (June 2021), for GitHub repositories with the "Open in Visual Studio Code" badge.
While the announcement was removed, it was replaced with Visual Studio Code for the Web.
The VSCode Web "Opening a project" section mentions:

You can navigate to a project repository directly from a URL, following the scheme: https://vscode.dev/SOURCE/ORG/REPO.
Using the VS Code repo as an example, this would look like: https://vscode.dev/github/microsoft/vscode.

And issue 128813 suggests:

I suggest we just use shields.io for this:
https://img.shields.io/static/v1?logo=visualstudiocode&label=&message=Open%20in%20Visual%20Studio%20Code&labelColor=2c2c32&color=007acc&logoColor=007acc

So the mardown would be:
[![Open in VS Code](https://img.shields.io/static/v1?logo=visualstudiocode&label=&message=Open%20in%20Visual%20Studio%20Code&labelColor=2c2c32&color=007acc&logoColor=007acc)](https://vscode.dev/SOURCE/ORG/REPO)

A: If you by native means in the GUI of the application, the answer is no. Though there is an open issue regarding this on their Github repository https://github.com/Microsoft/vscode/issues/9085 it doesn't look like they have the interest to implement it.
Even so, you can of course still clone a repository in your Terminal of choice and then handle the rest of your git functionality through the editor when you're working with the project.

A: I use github Desktop (https://desktop.github.com/) for both my github repos and gitlab repos


text:
Q: Debugging C++ project in Visual Studio 2010 I wrote a C# project in which I use a C++ dll (also written by me). I am trying to debug this dll function from my C# solution.
I have added C++ project to C# solution and manage its output - that's ok. But I could not get into the dll functions (break points not loaded).

A: Assuming you are using a version of Visual Studio that is not Express, you should be able to allow native C++ debugging by checking an option in the properties pane of the project you are running. Go to Project Properties -> Debug -> Enable unmanaged code debugging.

A: You will want to make sure that your native DLL was compiled and linked in debug mode. Though I don't work with the Visual Studio IDE much, the command line options you want are /Zi for cl.exe and /DEBUG for link.exe. This should result in the DLL being built with debug symbols enabled, and a .pdb file being generated. You should then be able to attach to the process as usual (you may have to do this from the Visual C++ debugger---again, I don't work much with the IDE) and set breakpoints on functions in the DLL.

A: Samuel Slade's answer is correct with one clarification:
I was trying to debug into an ATL/MFC C++ COM object from some C# code using Visual Studio 2010. I had a separate Solution for each project and could not make it work. When I put both projects into one Solution and enabled unmanaged code debugging as directed above, it worked wonderfully.
So cram both projects into one Solution and it should work.


text:
Q: Can't add Laravel Box to Vagrant I have been trying to install Laravel Homestead but it seems that I got stuck for several hours now. I followed the instructions here. I was able to edit the homestead.yaml and edit the paths for windows 7. I am using Git Bash to run everything so when I type $ vagrant up I get a whole bunch of errors.
c:/HashiCorp/Vagrant/embedded/lib/ruby/2.0.0/psych.rb:205:in `parse': (<unknown>
): did not find expected '-' indicator while parsing a block collection at line
12 column 5 (Psych::SyntaxError)
        from c:/HashiCorp/Vagrant/embedded/lib/ruby/2.0.0/psych.rb:205:in `parse
_stream'
        from c:/HashiCorp/Vagrant/embedded/lib/ruby/2.0.0/psych.rb:153:in `parse
'
        from c:/HashiCorp/Vagrant/embedded/lib/ruby/2.0.0/psych.rb:129:in `load'

        from c:/users/Designer1/Desktop/Code/Vagrantfile:17:in `block in <top (r
equired)>'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/c
onfig/v2/loader.rb:37:in `call'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/c
onfig/v2/loader.rb:37:in `load'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/c
onfig/loader.rb:103:in `block (2 levels) in load'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/c
onfig/loader.rb:97:in `each'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/c
onfig/loader.rb:97:in `block in load'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/c
onfig/loader.rb:94:in `each'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/c
onfig/loader.rb:94:in `load'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/v
agrantfile.rb:28:in `initialize'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/e
nvironment.rb:691:in `new'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/e
nvironment.rb:691:in `vagrantfile'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/e
nvironment.rb:441:in `host'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/e
nvironment.rb:207:in `block in action_runner'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/a
ction/runner.rb:33:in `call'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/a
ction/runner.rb:33:in `run'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/e
nvironment.rb:428:in `hook'
        from c:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.7.2/lib/vagrant/e
nvironment.rb:673:in `unload'
        from c:/HashiCorp/Vagrant/bin/../embedded/gems/gems/vagrant-1.7.2/bin/va
grant:177:in `ensure in <main>'
        from c:/HashiCorp/Vagrant/bin/../embedded/gems/gems/vagrant-1.7.2/bin/va
grant:177:in `<main>'

If anyone knows what am I doing wrong please help!


text:
Q: Filter and display content on the left based on navigation selection using angular Filter This should be a simple question, currently am displaying widget types on the left side of the navigation and i have a widget array. Based on the Widget Title selection i need to filter the types from the widget and display on the right.
Here is the code which i have right now,
App.js
 $scope.WidgetTypes = [
    {
       title: 'Chart',
      icon: 'styles/css/images/icons/ic_insert_chart_24px.svg'
    },
    {

      title: 'Blogging',
      icon: 'styles/css/images/icons/ic_assignment_24px.svg'
    },
    {

      title: 'Advertising',
      icon: 'styles/css/images/icons/ic_av_timer_24px.svg'
    },
    {

      title: 'Custom',
      icon: 'styles/css/images/icons/ic_dashboard_24px.svg'
    },
    {

      title: 'Social Media',
      icon: 'styles/css/images/icons/ic_now_widgets_24px.svg'
    } ,
     {

      title: 'Web Analytics',
      icon: 'styles/css/images/icons/ic_gradient_24px.svg'
    }
  ];
      $scope.Widgets = [
    {
       title: 'Google SpreadSheets',
      icon: 'styles/css/images/icons/ic_insert_chart_24px.svg',
       type:"Chart",
       Description:'Line, Area, Bar, Pie, Table'
    } ,

    {

      title: 'LinkedIn',
      icon: 'styles/css/images/icons/ic_dashboard_24px.svg',
       type:"Social Media",
         Description:'Connections, Network Updates'
    },
    {

      title: 'Pinterest',
      icon: 'styles/css/images/icons/ic_dashboard_24px.svg',
       type:"Social Media",
         Description:'Boards, Pins, Likes, Followers, Following'
    },
    {

      title: 'Google Analytics (Real Time)',
      icon: 'styles/css/images/icons/ic_dashboard_24px.svg',
       type:"Web Analytics",
         Description:'Audience, Traffic, Content, Conversions'
    }
  ];

HTML:
 <md-list-item class="md-3-line" ng-repeat="widget in Widgets ">

{{ widget.title }}

{{ widget.Description }}

       <md-button style="width:100px"    class="md-raised">
        Add
       </md-button>

   <md-divider></md-divider>
 </md-list-item>

Here is the Plunker

A: You in the right direction already you only have to implement which is selected & filter
$scope.filterWidgets = function(item)
 {
   $scope.selected = {};
  $scope.selected.type = item.title;
  console.log(selected);
 };

and
<md-list-item class="md-3-line" ng-repeat="widget in Widgets | filter : selected">

http://plnkr.co/edit/8M8tNAmV1dARIu4OfFcl?p=preview


text:
Q: Google App Engine: Users API acting oddly I think I'm using the Users API incorrectly:
class BaseHandler(webapp.RequestHandler):
   user = users.get_current_user()

   def header(self, title):
     if self.user:
        render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
     else:
        render('Views/link.html', self, {'text': 'Log in', 'href': users.create_login_url('/')})

link.html:

    {{text}}

Sometimes it works, sometimes it doesn't. I will click the "log out" link 10 times in a row, and reload the page, and it will redirect me to the '/' page. Then, mysteriously, one of the times I'll be logged out. Logging in fails in essentially the same fashion. What's going on here?
Solved - This works:
class BaseHandler(webapp.RequestHandler):

    def __init__(self):
        self.user = users.get_current_user()

    def header(self, title):
        if self.user:
            render('Views/message.html', self, {'msg': "Welcome, %s" % self.user.nickname()})
            render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
        else:
            render('Views/link.html', self, {'text': 'Log in', 'href': users.create_login_url('/')})

It looks like I can have instance variables by referring to them as self.var_name in a function, but never declaring them on a class level. Odd.

A: You are storing the result of users.get_current_user() in the variable called user, but then your if checks the value of self.user, which is not the same variable.
Use the same variable name and all should be fine!


text:
Q: Boyd & Vandenberghe, problem 3.51 — how to show that the number of roots is even? This question is related to Problem 3.51 of Convex Optimization. Consider a polynomial $p(x)$ which has $n$ roots i.e. $$p(x)=(x-s_1)(x-s_2)\cdots(x-s_n)$$ where we assume w.l.o.g. that $s_1\leq s_2\cdots \leq s_n$. In this case if the polynomial is positive in $$x\in (s_k,s_{k+1})$$ then how to show that the number of roots present on the right side of the interval $(s_k,s_{k+1})$ are even? Any help in this regard will be much appreciated. Thanks in advance.

A: The sign of $p(x)$ for $x \in (s_k,s_{k+1})$ is obtained by multiplying the numbers $\pm 1$ for each of the factors. Note that $x-s_j>0$ for $j <k$ and $<0$ for $j >k$. If there are an odd number of factors to the right of $(s_k,s_{k+1})$ then the value of $p$ in this interval would be negative.


text:
Q: Defining periodic functions? Consider $f: (a,a+p] \rightarrow \mathbb{R}$.
What is the "formula" for the p-periodic function $g$ which has the property that $g(x + np) = f(x)$ for all $x$ in $(a, a+p]$? I am well aware of how it looks like graphically, but in what formal notation is this function written, as a piecewise function?

A: Given $x \in \mathbb{R}$, there exists a unique $y \in (a,a+p]$ such that $x = y + np$ for some $n$. We usually write $y = x - a \pmod p$. It is as though $y$ were the remainder of the "division of $x-a$ by $p$", with the exception that $p$ need not be an integer.
In this notation, the function $g$ becomes simply $g(x) = f(x-a \pmod p)$.

A: Let $\lceil x \rceil$ be the ceiling of $x$. Then $\lceil x/p \rceil < x/p \leq \lceil x/p \rceil +1$, thus $a < x+a-p\lceil x/p \rceil \leq a+p$. We can now define the $p$-periodic function $g$:
$$
g:\mathbb{R}\to\mathbb{R}, \;x\mapsto f(x+a-p\lceil x/p\rceil).
$$


text:
Q: Google API key Vs. Google Client ID One of our customers is using google maps with a "Client ID". We've developed our product using the Google API Key. All of the features of the map are working properly using the API key, but we are unable to confirm that the client will get the same results with the  Client ID since we do not have one. Two question, do you believe that the features will work the same using either the API or the Client ID? Second question, how much does it cost to purchase a Client ID?

A: Client IDs and API Keys are forms of authentication and authorization. There are easy-to-follow guidelines on their proper usage and their limits. Everything you need to know about them can be found in the documentation (also try seeing the docs per product in the 'For more information' section):
https://developers.google.com/maps/premium/overview#authentication_and_authorization
Related SO post and answer about using Client IDs for their Javascript API:
google maps api javascript usage
For pricing, read more about it here:
https://developers.google.com/maps/pricing-and-plans/
EDIT: There has been recent Google Maps Platform pricing and product changes You'll always need an API key and a valid billing account associated to your Project if you want to use the Google Maps Platform APIs. If you've never had a Client ID then you don't need to worry about it, just continue using your API keys.
You may run into some APIs (i.e. Speed Limits API)  that seem to need a Premium Plan account. If you really need access to these, simply contact sales using this form.
P.S.
When using API keys, be sure to properly restrict them!


text:
Q: Bounds for the number of points on projective hyperelliptic curves over finite fields Let $C$ be projective hyperelliptic curve over finite field $K$.
What are bounds for the number of points $\#C(K)$?
The Hasse-Weil bound requires smooth curves, and hyperelliptic curves are
not smooth if the degree is greater than three, having only one singular point.
We have explicit example violating the Hasse-Weil bound with only one singular point.
abx claims "A projective hyperelliptic curve is smooth by definition."
For counterexample to abx take $x^6+z^6=y^2 z^4$ and observe that it has singular point over the rationals.
Take $p=29,K=GF(p), C: -4 x^4+z^4-z^2 y^2=0$.
According to sage, this hyperelliptic curve violate the Hasse-Weil
bound, what is wrong with this argument?
sage session:
p=29
K.<x,y,z>=GF(p)[]
f= -4*x^4+z^4-y^2*z^2
C=Curve(f)
print(abs(p+1-len(C.rational_points())),2*sqrt(1.0*p))
#11 10.7703296142690

A: For simplicity, let $q$ be odd. The question is to bound $\mathbb{F}_q$ points on $y^2 = f(x)$ when there are singularities. Write $f(x) = u(x) v(x)^2$ where $u$ is square free. Let $X$ be the affine curve $y^2 = f(x)$ and let $\tilde{X}$ be the normalization $z^2 = u(x)$, so these are birational by $(x,z) \mapsto (x, v(x) z)$.
Let the degree of $u$ be $2g+r$ where $r=1$ or $2$. Then $\tilde{X}$ is a genus $g$ curve with $r$ punctures, so the Weil bounds for $\tilde{X}$ are
$$-2 g \sqrt{q}-r \leq \#\tilde{X}(\mathbb{F}_q) - q -1 \leq 2 g \sqrt{q}.$$
Let $m$ be the number of distinct roots of $v$ in $\mathbb{F}_q$. At each root of $v$, the map $(x,z) \mapsto (x, v(z) x)$ might create a new $\mathbb{F}_q$-point (if $x$ is in $\mathbb{F}_q$ and $z$ is not) or might merge two $\mathbb{F}_q$-points into one. (It also might send one $\mathbb{F}_q$-point to one such point, if $z=0$.) So the bounds for the original affine curve are
$$-2 g \sqrt{q}-r-m \leq \#X(\mathbb{F}_q) - q -1 \leq 2 g \sqrt{q}+m.$$
Finally, if you want to count points on the closure of $X$ in $\mathbb{P}^2$, add in one more point at $\infty$, giving
$$-2 g \sqrt{q}-r-m+1 \leq \#\overline{X}(\mathbb{F}_q) - q -1 \leq 2 g \sqrt{q}+m+1.$$


text:
Q: Keras throws an error when running with sudo When I run my Keras training script with sudo sudo KERAS_BACKEND=theano python train.py I get an error after some time:
Traceback (most recent call last):
  File "train.py", line 186, in <module>
    loss=siamese_net.train_on_batch(inputs,targets)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1565, in train_on_batch
    outputs = self.train_function(ins)
  File "/usr/local/lib/python2.7/dist-packages/keras/backend/theano_backend.py", line 1197, in __call__
    return self.function(*inputs)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.py", line 898, in __call__
    storage_map=getattr(self.fn, 'storage_map', None))
  File "/usr/local/lib/python2.7/dist-packages/theano/gof/link.py", line 325, in raise_with_op
    reraise(exc_type, exc_value, exc_trace)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.py", line 884, in __call__
    self.fn() if output_subset is None else\
  File "/usr/local/lib/python2.7/dist-packages/theano/gof/op.py", line 872, in rval
    r = p(n, [x[0] for x in i], o)
  File "/usr/local/lib/python2.7/dist-packages/theano/tensor/blas.py", line 1544, in perform
    z[0] = numpy.asarray(numpy.dot(x, y))
MemoryError:
Apply node that caused the error: Dot22(InplaceDimShuffle{1,0}.0, Elemwise{Composite{(i0 * i1 * (i2 - i1))}}[(0, 1)].0)
Toposort index: 162
Inputs types: [TensorType(float32, matrix), TensorType(float32, matrix)]
Inputs shapes: [(112896, 32), (32, 4096)]
Inputs strides: [(4, 451584), (16384, 4)]
Inputs values: ['not shown', 'not shown']
Outputs clients: [[Gemm{inplace}(Dot22.0, TensorConstant{1.0}, InplaceDimShuffle{1,0}.0, Elemwise{Composite{(i0 * i1 * i2 * (i3 - i2))}}[(0, 1)].0, TensorConstant{1.0})]]

HINT: Re-running with most Theano optimization disabled could give you a back-trace of when this node was created. This can be done with by setting the Theano flag 'optimizer=fast_compile'. If that does not work, Theano optimizations can be disabled with 'optimizer=None'.
HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.

However, when I just execute the python script without sudo KERAS_BACKEND=theano python train.py, it starts behaving as expected, at least as far as I have seen. How is this possible?


text:
Q: How to let only numbers or "n/a" to write to a specific column with data validation? I have a column where a user can only write company codes (integers), and in case of no company codes they can write "n/a". Is it possible to do this with data validation? To sum up, they can write only one string ("n/a") or any number.

A: Use a custom formula:
=OR(ISNUMBER(A1),A1="n/a")


text:
Q: The api returns both an object and an array I'm new to json, there was a problem and I couldn't find a solution
I was given an api and when executing a get request, I get some object, but if there is no data in the object, an array is returned.
At the moment I was able to get Any?, instead of JSONArray or JSONObject, but there was a problem with converting Any? to the class
How to convert data to kotlin data class correctly?
returned object
returned array
The class I'm converting the json request to:
data class ProductInfo (var product:Product?,var specifications: JsonObject?,var supplements: Any?,var files:List<File>?,var feedback: Feedback?)

A: This seems something that the backend has to solve for you. They can give you a nullable array or just an empty array, whatever is more convenient, but implementing polymorphism is not something trivial.
Jackson makes polymorphism easier than Gson, however, it is always required some kind of anchor to know how to route the parsing, in this case, you don't have any.
Jackson uses an annotation and there you have indicate in which thing is going to pivot:
@JsonSubTypes.Type(value = Nothing.class, name = "????")

With Gson you have to implement your own JsonDeserializer but again, how do you know what type is it? If it can be cast to array then is nothing? Just writing that seems like an antipattern.


text:
Q: Como ajustar o formato dd/mm/yyyy Tenho o seguinte código que pega a data instantânea do computador.
#include <Windows.h>
#include <stdio.h>
#include <time.h>

void main () {
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);

    printf("Agora: %d/%d/%d", tm.tm_mday, tm.tm_mon+1, tm.tm_year+1900);
}

Eu preciso guardar a data fornecida em uma variável e eu suponho, pelo enunciado do meu exercício, que ele deve estar no formato dd/mm/yyyy, pois há uma necessidade posterior de pesquisa por meio da data.
Qual seria o método mais fácil de se adicionar as barras? Varrer o vetor com a data e em cada posição ir colocando a barra (foi o que pensei), ou há alguma solução mais eficiente?
Há uma certa dúvida no enunciado quanto a data estar no formato acima, mas não quero correr o risco e tentar por este formato. A pesquisa a qual me referi é o usuário informando duas datas (início e fim) e pesquisar todos os cadastros realizados nesta data.
Qualquer dúvida, perguntem.

A: Se quiser apenas guardar em uma variável, pode usar o sprintf no lugar do printf:
#include <Windows.h>
#include <stdio.h>
#include <time.h>

void main () {
    char minhaString[30];
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);

    sprintf( minhaString, "Agora: %d/%d/%d", tm.tm_mday, tm.tm_mon+1, tm.tm_year+1900 );
}


text:
Q: How to install a RPM package in a right way? I know its very basic question(but i am new to centos7), and very much confused, the examples i have checked over net someone is using YUM or first wget or tarball.Please tell the right way to install a software in centos7.
I was installing skype for centos 7. Firstly i checked its rpm package over=http://www.rpmfind.net/linux/rpm2html/search.php?query=skype&submit=Search+...
and after that copied that link and used the command=> wget copied url.
And i think its successfully downloaded, this is what its showing
[root@server ~]# wget ftp://195.220.108.108/linux/sourceforge/s/sn/snowbird/yum/sb20/skype-4.2.0.13-2.fc20.i686.rpm
--2017-02-10 12:17:25--  ftp://195.220.108.108/linux/sourceforge/s/sn/snowbird/yum/sb20/skype-4.2.0.13-2.fc20.i686.rpm
           => 'skype-4.2.0.13-2.fc20.i686.rpm'
Connecting to 195.220.108.108:21... connected.
Logging in as anonymous ... Logged in!
==> SYST ... done.    ==> PWD ... done.
==> TYPE I ... done.  ==> CWD (1) /linux/sourceforge/s/sn/snowbird/yum/sb20 ... done.
==> SIZE skype-4.2.0.13-2.fc20.i686.rpm ... 11673644
==> PASV ... done.    ==> RETR skype-4.2.0.13-2.fc20.i686.rpm ... done.
Length: 11673644 (11M) (unauthoritative)

100%[======================================>] 11,673,644  1.65MB/s   in 7.4s

2017-02-10 12:17:35 (1.51 MB/s) - 'skype-4.2.0.13-2.fc20.i686.rpm' saved [11673644]

Please tell me what to do further to install it.

A: To install software you first need to obtain it. There are several ways to do so and the wget method you used is one of them.
Next step is to actually install the software package and you have the two options yum and rpm. The method rpm -i skype-4.2.0.13-2.fc20.i686.rpm will try to install the package but can complain about unmet dependencies. yum install skype-4.2.0.13-2.fc20.i686.rpm will check for dependencies and will try to resolve them and provide you a detailed installation plan which you can accept to actually install the package including all its dependencies.
Within a desktop environment you might even open the downloaded rpm package using a file explorer and install from there.
In a lot of cases the installation steps are properly described on the website of the package maintainer so please read the installation manual which often describes which requirements there are and which steps you need to follow.
As a side note I would recommend to you to download the package from the vendors site if possible to have the most recent/appropriate version. If it can not be obtained from there you can download the most applicable version from rpmfind or similar sites. In this particular case Microsoft has version 4.3 available and you downloaded version 4.2.


text:
Q: transpose column to row oracle I have a query returned value in this form (query return more than 50 columns).
 1-99transval  100-200transval  200-300transval ... 1-99nontransval 100...
   50              90                 80                  67           58

For a row value. I want these details to be converted into columns and take the following shape:
Range       Transval      NonTransval
1-99        50            67
100-200     90            58

A: In pure SQL, it will need a lot of coding because you will have to manually put the range as there is no relation between the values and the range at all. Had there been a relationship, you could use CASE expression and build the range dynamically.
SQL> WITH DATA AS
  2    (SELECT 50 "1-99transval",
  3      90 "100-200transval",
  4      80 "200-300transval",
  5      67 "1-99nontransval",
  6      58 "100-200nontransval",
  7      88 "200-300nontransval"
  8    FROM dual
  9    )
 10  SELECT '1-99' range,
 11    "1-99transval" transval,
 12    "1-99nontransval" nontransval
 13  FROM DATA
 14  UNION
 15  SELECT '100-200' range,
 16    "100-200transval",
 17    "100-200nontransval" nontransval
 18  FROM DATA
 19  UNION
 20  SELECT '200-300' range,
 21    "200-300transval",
 22    "200-300nontransval" nontransval
 23  FROM DATA;

RANGE     TRANSVAL NONTRANSVAL
------- ---------- -----------
1-99            50          67
100-200         90          58
200-300         80          88

From Oracle database 11g Release 1 and above, you could use UNPIVOT
SQL> WITH DATA AS
  2    (SELECT 50 "1-99transval",
  3      90 "100-200transval",
  4      80 "200-300transval",
  5      67 "1-99nontransval",
  6      58 "100-200nontransval",
  7      88 "200-300nontransval"
  8    FROM dual
  9    )
 10  SELECT *
 11  FROM   DATA
 12  UNPIVOT( (transval,nontransval)
 13  FOR RANGE IN ( ("1-99transval","1-99nontransval") AS '1-99'
 14                ,("100-200transval","100-200nontransval") AS '100-200'
 15                ,("200-300transval","200-300nontransval") AS '200-300'));

RANGE     TRANSVAL NONTRANSVAL
------- ---------- -----------
1-99            50          67
100-200         90          58
200-300         80          88

Above, in your case you need to replace the WITH clause with your existing query as a sub-query. You need to include other columns in the UNION.
In PL/SQL, you could (ab)use EXECUTE IMMEDIATE and get the "range" by extracting the column names in dynamic sql.
Although, it would be much better to modify/rewrite your existing query which you have not shown yet.

A: If you are using Oracle 11g version then you can use the UNPIVOT feature.
CREATE TABLE DATA AS
SELECT 50 "1-99transval",
    90 "100-200transval",
    80 "200-300transval",
    67 "1-99nontransval",
    58 "100-200nontransval",
    88 "200-300nontransval"
  FROM dual

SELECT *
FROM   DATA
UNPIVOT( (Transval,NonTransval) FOR Range IN ( ("1-99transval","1-99nontransval") as '1-99'
                                            ,("100-200transval","100-200nontransval") as '100-200'
                                            ,("200-300transval","200-300nontransval") as '200-300'))

http://sqlfiddle.com/#!4/c9747/3/0