text:
Q: What is the best approach for displaying private images from AWS S3 bucket? I have a webapp and each user can upload images to a private AWS S3 bucket.

In the desired page each user can view his images. Unlike other files (text / csv files etc...), these images should be displayed immediately when the page loads and not downloaded to the local computer one by one.
To display the relevant images to the user I found few ways:

*

*Download the images in the server directly and send them as HTTP response to the user.

*Use presigned URLs and if the image is expired a request will be sent to refresh the presigned URL from the server. The new URL will be sent to the user and will be saved in the DB as well that the next time a user requests for the image he has the updated presigned URL.

The first approach is not ideal.

The second approach sounds more efficient, but let's assume a page contains dozens of images that should be displayed and all the presigned URLs have expired. Should I take this approach altough it might end with dozens of requests just for refreshing the presigned URLs? As far as I know it is a problem because there isn't an option the generate presigned URL without expiry (7 days max) and there isn't an option for generating presigned URL for entire directory instead of an object. And what happens to browser caching when presigned URLs are refreshed?
I am wondering what is the best approach for displaying the private images that cannot be shared between users.
Any suggenstions?
Thanks.


text:
Q: validate an array of Enum in yup I need to validate an array of enums in yup.
I am using typescript so I have to utilize the exact type of the enums during validation. While using an array of strings seems to work, I want to validate the exact array of enums instead of strings. Is there a way to accomplish this?
I've added a working codesandbox as well
https://codesandbox.io/s/clever-edison-3vqp1
Here's a snippet of what I intend to do
import { object, array } from "yup";

enum DayEnum {
  Sunday = "Sunday",
  Monday = "Monday",
  Tuesday = "Tuesday",
  Wednesday = "Wednesday",
  Thursday = "Thursday",
  Friday = "Friday",
  Saturday = "Saturday"
}

const daysSchema = object({
  // days_of_week: array(string()),
  days_of_week: array(DayEnum)
});

const main = async () => {
  console.log(
    await daysSchema.isValid({
      days_of_week: [DayEnum.Sunday, DayEnum.Saturday]
    })
  );
};

main();

A: I was able to solve this thanks to this comment: https://github.com/jquense/yup/issues/1497#issue-1034140602
The solution looks like this
const daysSchema = object({
  days_of_week: array(
        mixed<DayEnum>().oneOf(Object.values(DayEnum)).required()
    ).ensure()
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to inline string without const enum? I want to expoort string contsnt but in such way that it would be inlined in all places it is used it and variable von't be created. I know it's possible with const enum:
const enum SomeEnum {
    SOME_VALUE = "SOME_VALUE"
}

alert(SomeEnum.SOME_VALUE);

compiles into
"use strict";
alert("SOME_VALUE" /* SOME_VALUE */);

But I'm interested in making dotless access to the value, i. e. I want to write
alert(SOME_VALUE);

and I want it to be compiles into the same thing.
How can I declare SOME_VALUE to archive that?

A: As of 2020-09, you cannot,
Here's a discussion about such a feature — inline constants — over at the Typescript GitHub repo: https://github.com/microsoft/TypeScript/issues/3964
Update: Now that issue got closed:

given the feedback so far and the risk of the feature, it's safe to say this isn't happening

So, likely Never, then.


text:
Q: Why is StarCraft 2 divided by regions? I live in Argentina, but I love to get all my stuff (be it games, tv series, movies, etc) in English.
Battle.net will only let me select one region, which by default is Latin America, that has only Spanish and Portuguese (not to mention that I only get to play with users in the same region).
What is the logic behind this? Is there a way to play in any region and in any language? (legally of course)

A: The short answer is because Starcraft 2 is region-locked, like most videos, games, and game consoles.
The easiest way to circumvent this region locking is to simply purchase another copy of the game from the region you're seeking to join.
The patient route is to wait until Blizzard gets around to implementing cross-region battle.net.
Edit: Too bad you don't live in Australia: http://www.kotaku.com.au/2010/07/starcraft-ii-will-not-be-region-locked-in-australia/

A: I sent an e-mail to blizzard support, this is what they answered:

Quality and customer service are the highest priorities for Blizzard Entertainment. Because we cannot guarantee a positive gaming experience for users connecting to servers outside the supported region, we do not support use outside of the designated region. You can change which region you are purchasing for by clicking the (change) link next to the region.  I recommend that, if possible, you acquire a localized version of the game for a more positive gaming experience.
In other words, players in one region of the world will not be able to play on alternate regions at this time. This is something that we will continue to investigate as a possibility for the future, however, if you have purchased a version of StarCraft II from outside of your home region we recommend that you return it and purchase the localized version instead.
Please also keep in mind that you will not be able to access your account if you are using a different regional game version (other than your home regions version). For example, you will be unable to connect to the North American realms if using a Chinese, Korean, European, or Taiwanese version of the game.
We recommend that you continue to visit http://us.battle.net/sc2/en/ for the latest announcements and updates on this and other StarCraft II features.
If you have additional questions or concerns, please reply to this email.  If you would rather speak with a representative directly, please contact Account & Technical Services. Our contact information can be found at http://blizzard.com/support/article/cs.

A: The another reason is maybe because of different pricing policy made by Blizzard. For example unlimited euro version costs 60 euro, while russian one is twice chipper. Maybe somebody will be unpleased that he had to pay more then another for the same server.

A: There might be a legitimate concern over latency.  I know the Internet is pretty international, but the simple fact is if I'm in Alberta, my average latency relative to someone in Texas will generally be shorter than my latency relative to someone in South Africa.

A: The reasons invoked by Activision are absolute garbage. In SC1 we could simply reconnect to a different server OF YOUR CHOICE. The real reason is that your account is tied to a specific server. If you have a bro/sis, you need another account and you need to buy another copy. It all boils down to milking your fanbase for more money.

A: Why is StarCraft 2 divided by regions?
Blizzard/Activision decided so and for the moment, you cannot do anything about it.
I love to get all my stuff [...] in English
You could try to persuade Blizzard/Activision to add the English language to your region. It might actually be easier than opening the regions since the English version is already available in other regions.
I bought Starcraft 2 in France and got a French version, but I was able to download an English version from the European Battle.Net server.


text:
Q: Storing the OAuth credentials from DropBox securely in a Database for later use I am building a web app which will use the DropBox API to save data to a users folder. There are 2 parts to the site: an ASP.NET MVC Front End and a Windows Service. At the moment, I was planning on dumping the oauth string and user Id from the authorisation request to database, and use that in both the service and website calls, but how should I store that information? Should I encrypt it or not? And if so, any recommendations on how? For example, if the database is encrypted, how do I store the Encryption key?

A: Do you want to always have access to the user's drop box account or only when they are loged in to your system ?  I assume the former since you want to store the o-auth token. In that case see the encryption discussion below for why you can't really encrypt it. I'd suggest however, that you take the safer route and only access drop box either when the user is loged in or shortly their after (i.e. don't store persistent auth tokens )
The secure approach
When the user logs in, get an oauth token from the dropbox, use it to perform whatever actions they want and if necessary keep it around after the log out to keep doing tasks ( background sync or something). However, once that last task finishes, delete the token. This means that if your server is compromised only the loged in users or those that recently loged out are exposed. Its a mitigation, but its the best you can get.
I believe you can do this with o-auth without explicitly prompting the user for a new token every time. If not, I know you can do it with opendID, though I could see drop box not allowing that.
Finally, if neither of those works, you could store the o-auth key persistently encrypted under a key derived from the users password with say PBKDF2(with like 5000 iterations). When they log in, you decrypt it, use it, and then delete the cleartext copy. The downside to this is 1) password resets require a fresh o-auth token since you no longer have their key and 2) the user must log into your site itself and give you a password so you can derive the key. They cannot  use openid.
Encryption
If you want continual access to the oauth tokem you can't really do meaningful encryption. As you said, where would you store the key ? For a web service, there is no good answer. For an end user system, the answer is derive the key from the user's password which you the must not store(this is what lastpass does). You can't do this because you want to have access to the data even when the end (wepapp) users are not loged in.
Ok, what about the sysadmin's password? Well since the server is running all the time, this is worthless since a compromise would still reveal the keys. Worse, reboots would take down your app because it needs the sys admin's password to decrypt its data and they are not likely their when the system crashes at 3am.
They make Hardware Security Modules that store keys and perform crypto operations with them, so  an attacker could  get the key because it never leaves the HSM. However, an attacker could just ask the TPM to decrypt the o-auth string. The best you could do was rate limit this so an attack could only get like 1000 tokens an hour (obviously that rate needs to be larger that legit usage). Given that HSMs are expensive and make hosting expensive because you need a dedicated system, this is not worth it.
In an ideal world, you'd use a TPM to hold the keys and have it only release the data if the system is not compromised. Unfortunately, TPM's currently only support verifying that the correct program (e.g. the boot-loader,then kernel, then user land program) was loaded. They do nothing if that program is compromised after it is loaded, which is the threat vector here. This might change in the next 5 to 10 years, but that does not help you now.


text:
Q: Twillio Studio gather/split using first input New to Twilio Studio.
I have a "chain of events" that all play a "message" and gather DTMF/ touch TONES. [Gather input/split based on]
If I press "4" on the first gather/split, on the second gather/split it will always choose "4" even if I press "1" and ignore my actual input.
Do I have to re-initialize the input buffer somehow?  How can I get the second gather/split to respond to the actual input?

A: Check the variable you are evaluating on the next split based on widget refers to the most recent gather widgets input.
You can also view the Studio execution logs to view the underlying evaluation logic.
Split Based On... Widget


text:
Q: Silverlight PivotViewer Semantic Zoom Two PivotViewerTemplates Displayed Simultaneously I am using a PivotViewer control in a Silverlight 5 User Control.  I have two PivotViewerTemplates defined to take advantage of Semantic Zoom.  The first template defined has a MaxWidth of 300, the second template has no MaxWidth set.  At a certain "zoom" within the PivotViewer control, both PivotViewerTemplates are being displayed simultaneously (both templates are somewhat transparent at that time as well).  It is almost as if it is stuck between transitioning from one PivotViewerTemplate to the other.
How can I prevent both PivotViewerTempaltes from being displayed simultaneously?

A: What you are seeing is the transition effect between two templates. When doing a large scale transition it provides a smooth animation. However, it can be a bit sticky depending your MaxWidth and the number of items in your collection.
You will find that if you play with the MaxWidth you can minimize the effect for your collection.


text:
Q: AS3: Using embedded font I embed font like this (FlashDevelop):
[ Embed( source = "Ubuntu-R.ttf", embedAsCFF = "false", fontFamily = "Ubuntu" ) ]
private static const Ubuntu : Class;

Then try to use like this:
var textField : TextField = new TextField;
textField.embedFonts = true;
textField.defaultTextFormat = new TextFormat( "Ubuntu", 22 );
textField = "免費旋轉 ПРИВЕТ HELLO";
addChild( textField );

Only russian and english parts of the text visible, but not japanese (my PC is russian). If to comment textField.embedFonts = true; line, then the whole text will be visible, but some other (seems like Arial) font used.
Call to Font.enumerateFonts( false ); returns array with one font called "Ubuntu".
Call to Font.registerFont( Ubuntu ); at any place doesn't help.
Adding parameters fontName, unicodeRange = "U+0000-U+FFFF", mimeType = "application/x-font-truetype", fontWeight, advancedAntiAliasing to the font embed directive with different attributes do not change the behavior.
Seems like dead end, but please help.

A: The font you use does not contain the required glyphs for Japanese. You might try another font, make sure though it has enough glyphs in there. A hint: if the font isn't as big as 1 megabyte, most likely it has neither japanese nor chinese glyphs, if it's bigger, then try embedding and check with hasGlyphs() if it has enough. Once you'll find the correct font, embed and enjoy. But, I'd say use a font that's widely distributed and has japanese glyphs by design, say Arial.


text:
Q: UnknownHostException is not recognized in catch block One of the method in my code throws UnknownHostException exception
I first had a catch block like this:
catch (Exception e) {
  // TODO Auto-generated catch block
  System.out.println("Custom Message "+e.getMessage());
  if(e instanceof java.net.UnknownHostException){
      System.out.println("Unknown Host Ex");
  }else{
      System.out.println("OTHER ERROR");
  }
}

I am facing a problem where that if condition never evaluates to true and hence I am not able to output that there is some host error.
You can see I have a sysout just before that which prints this :
Custom Message ; nested exception is:
    java.net.UnknownHostException: abc.xyz

After that I wrote a seperate catch block to handle UnknownHostException but still is it not getting catched.

A: UnknownHostException is nested inside another Exception so it may not be an instance of it but it just contains it. You may eventually check e.getCause()

A: Well, apparently your UnknownHostException in wrapped in some other exception. In other words some code above catches UnknownHostException and throws:
throw new SomeOtherException("Custom Message", unknownHostEx);

Print e.getClass() to see what kind of exception is wrapping it. You can also try:
if(e.getCause() != null && e.getCause() instanceof UnknownHostException)

but it's ugly.
BTW you should avoid using instanceof and let catch figure out the exception itself (but it won't help in your case):
catch (java.net.UnknownHostException e) {
      System.out.println("Unknown Host Ex");
}
catch (Exception e) {
      System.out.println("OTHER ERROR");
}


text:
Q: Запуск JARа скомпилированного из проекта Maven Разработал проект Maven в NetBeans.
Пытаюсь его запустить с JAR-ника командой

java -cp MyProject-0.1.0.jar ru.com.myproject.Main

где

ru.com.myproject.Main

есть главный класс, потому несмотря на то что я указал главный класс в
Свойства проекта > Выполнить > Главный класс
он все равно не указывается в манифесте...
Получаю ошибку:
Exception in thread "main" java.lang.NoClassDefFoundError: com/thetransactioncompany/jsonrpc2/JSONRPC2Parser
        at ru.com.myproject.<clinit>(Main.java:28)
Caused by: java.lang.ClassNotFoundException: com.thetransactioncompany.jsonrpc2.JSONRPC2Parser
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
        ... 1 more

Содержимое файла pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ru.com</groupId>
    <artifactId>MyProject</artifactId>
    <version>0.1.0</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.thetransactioncompany</groupId>
            <artifactId>jsonrpc2-base</artifactId>
            <version>1.38</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.1</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.surefire</groupId>
            <artifactId>maven-surefire-common</artifactId>
            <version>2.17</version>
            <type>jar</type>
        </dependency>
    </dependencies>
</project>

Так как же собрать проект Maven в NetBeans так что бы правильно был настроен manifest-файл: был правильно прописан главный класс и зависимости ?
Или как вообще запустить собранный проект Maven ?

A: Java не может найти зависимости, в частности jsonrpc2. Можно либо добавить их jar-файлы в CLASSPATH, либо упаковать в один jar. Первое можно сделать как вручную, так и с помощью maven-dependency-plugin:
<project>
    ...
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.10</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    ...
</project>

Второе с помощью maven-assembly-plugin:
<project>
    ...
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>fully.qualified.MainClass</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
    ...
</project>


text:
Q: node-mongodb findOne behavior I have a strange issue that I can't quite seem to explain.  Given the following:
Generics.prototype.getCollection= function(collection,callback) {
  this.db.collection(collection, function(error, document_collection) {
    if( error ) callback(error);
    else callback(null, document_collection);
  });
};

Generics.prototype.findById = function(collection, id, callback) {
    this.getCollection(collection,function(error, document_collection) {
      if( error ) callback(error)
      else {
        document_collection.findOne({_id: document_collection.db.bson_serializer.ObjectID.createFromHexString(id)}, function(error, result) {
          if( error ) callback(error)
          else callback(null, result)
        });
      }
    });
};

Generics.prototype.findOne = function(collection, _key, _value, callback) {
    this.getCollection(collection,function(error, document_collection) {
      if( error ) callback(error)
      else {
        document_collection.findOne({_key:_value}, function(error, result) {
          if( error ) callback(error)
          else callback(null, result)
        });
      }
    });
};

findById works like a charm.  However, findOne always returns null when executed.  I fired up node-debugger to find out what the deal was and I discovered that one of the passed variables is being destroyed/erased somehow.  _key always seems to be erased.  _value however is always there.  I tried renaming _key to something else and no matter what, it's always erased.  Any ideas as to what might be happening would be appreciated.  thanks!
Update
I just refactored a bit to allow for a more flexible search query and made it work with one variable.  I'd still like to know what's going on.  I feel like it's some closure business that i'm not quite understanding.
Generics.prototype.findOne = function(collection, searchKeys, callback) {
    this.getCollection(collection,function(error, document_collection) {
      if( error ) callback(error)
      else {
        document_collection.findOne(searchKeys, function(error, result) {
          if( error ) callback(error)
          else callback(null, result)
        });
      }
    });
};

A: Javascript would always treat the key of object as a string if you use the {} syntax as you did when you passed it to the findOne method:
{_key:_value}

In other words, the object above is basically treated as:
{ '_key': _value }

which I don't think is what you want. One common approach to overcome this is to create an object and use the [] operator like this:
var temp = {};
temp[_key] = _value; // here, the _temp symbol is interpreted as a js variable


text:
Q: Which version of coreclr? In the .NET CLI I can use the switch --version to get the version of CLI. Is there a similar way to get the version of the coreclr ?

A: No more dnvm.
The version of coreclr is determined in your project.json file.
Also there is a shared runtime when you install dotnet cli. You can find it in dotnet cli folder.
If your applicaiton have not specified any runtime in project.json then you app is portable and will run using shared runtime. You can specify multiple runtimes and your application binaries will be compiled for all this runtimes separately.
UPDATED:
Adding link to .NET Platform Standard documentation describing new way to design API in .NET
Link to David Fowl's GitHub repository describing .NET Platform Standard
Here is an example where runtimes are specified
{
  "version": "1.0.0-*",
  "compilationOptions": {
    "warningsAsErrors": true,
    "preserveCompilationContext": true,
    "emitEntryPoint": true
  },
  "dependencies": {
       ...
  },
  "frameworks": {
    "net451": {
      "dependencies": {
        ....
      }
    },
    "netcoreapp1.0": {
      "imports": [
        "dnxcore50",
        "portable-net45+win8"
      ],
      "dependencies": {
        "NETStandard.Library": "1.5.0-rc2-24018",
        "Microsoft.DotNet.ProjectModel": "1.0.0-rc2-002416"
      }
    }
  },
  "content": [
    "config.json"
  ],
  "runtimes": {
    "win7-x64": {},
    "win7-x86": {},
    "osx.10.11-x64": {},
    "ubuntu.14.04-x64": {},
    "centos.7-x64": {},
    "rhel.7.2-x64": {},
    "debian.8.2-x64": {}
  }
}

A: The version of the coreclr is in our application's project.json. dnvm list -detailed (from the previous toolchain) shows us runtime info which is completely irrelevant to the dotnet toolchain.
> dnvm list -detailed
Active Version         Runtime Architect OperatingSystem Alias   Location
------ -------         ------- --------- --------------- -----   --------
       1.0.0-rc2-16595 coreclr x64       win                     C:\Users\me\.dnx\runtimes
  *    1.0.0-rc2-20221 clr     x86       win             default C:\Users\me\.dnx\runtimes

We can find the equivalent dotnet relevant information:

*

*Version and Runtime are in project.json's frameworks section (e.g. netcoreapp1.0, net451).

*Architecture and Operating System are in project.json's runtimes section (e.g. win7-x64).

*Location is our NuGet global-packages folder (nuget locals all -list) after restore and our project's bin after build.

*Alias and Active are obsolete.

"There's no dnvm replacement" for the .NET CLI and no command to "get the version of the coreclr." That is because the runtime is now fully specified in our project.json and installed with the dotnet restore command.
With the dnu/dnx/dnvm toolchain, we installed the runtime independently from our application and its dependencies.

*

*We used dnvm install|upgrade|use to download and use a runtime; dnvm did not consult project.json.

*We used dnu restore to download application specific dependencies; dnu did consult project.json.

With the dotnet toolchain the restore operation combines those two steps. It consults our project.json and downloads both the runtime and the dependencies.
dnvm does not interact with the dotnet toolchain. In fact, we can delete the ~/.dnx directory and dotnet will build our project.

A: The existing answers probably have all the information, but that's in part obscured by legacy information, so let me attempt a pragmatic summary as of .NET Core v2.0 beta.

*

*While there is a globally active SDK version, as reported by dotnet --version[1]
,

*there's no globally active runtime (CoreCLR) version - runtimes are installed side-by-side, and each project determines which runtime it targets, by way of its *.csproj file.
To list all installed CoreCLR versions:

*

*In bash:

*

*ls -1 "$(dirname "$(which dotnet)")/shared/Microsoft.NETCore.App"

*In PowerShell Core (both Windows and Unix):

*

*(Get-ChildItem "$((Get-Command -Type Application dotnet).source)/../shared/Microsoft.NETCore.app").Name
To inspect a given project's target CoreCLR: (run the commands in the project root folder):

*

*In bash:

*

*awk -F '</?RuntimeFrameworkVersion>' 'NF>1 {print $2}' *.csproj

*In PowerShell Core (both Windows and Unix):

*

*([xml] (Get-Content -Raw *.csproj)).Project.PropertyGroup.RuntimeFrameworkVersion
For a PowerShell Core script that wraps this functionality and more, see this Gist of mine.

[1] Optionally, on a per-project basis, you can override the globally active SDK version by placing a global.json file in the project folder - see the docs.
Also note that just running dotnet without parameters or running dotnet --version without the SDK installed will show text that reflects the shared host ("driver") version - this obscure and confusing behavior is being discussed on GitHub here.


text:
Q: Pulling columns from Active Directory Search window ("The Find User, Contacts and Groups" search window) I would like to pull and list (I don't really care where, in a DataTable, textbox, etc) all the columns and properties name of the Active Directory Search window (column name like Name, First Name, Last Name, etc)
I think the DirectorySearcher assembly can achieve that but all the examples I find are examples with fields and properties already known.

A: Active Directory is a Directory Service based on LDAP. To query a directory, you must know the property names. Here is a pretty expansive list you can use

A: If you're on .NET 3.5 and up, you can use a PrincipalSearcher and a "query-by-example" principal to do your searching:
// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a UserPrincipal
UserPrincipal qbeUser = new UserPrincipal(ctx);

// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
    string firstname = found.GivenName;
    string familyname = found.Surname;
    // and so on
}

If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement


text:
Q: Multivariant wilcox.test() in r I know that wilcox.test it's used when you need to check if two samples of one no parametric independent variable are coming from the same population.
The thing is that r allows you to do wilcox.test(formula =  W + Y + Z ~ X, data = mydata) and returns me a different value that when I use the formula Y ~ X.
What is r showing me?
Shouldn't I do a T^2 Hotteling with p-value calculated with permutations for non-parametric distributions? With is the difference between this W + Y + Z ~ X in a wilcox.test?
Thanks,

A: As @Peyton point, the problem is that, in contrast to other 'formula' styles, in here just add the different components of the vector.
When a formula is introduced into r function use to be in the form of: Dependent variable ~ Independent Variable 1 + Independent Variable 2, + ... + Independent Variable n. This work this way in most common and usual functions like lm(), glm() or caret package.
But it seems like wilcox.test() -despite it accept this form- is operating with variables. In the case I expose is adding it.


text:
Q: UWP - Background task - UI - how to hide the UI? I'm working on a UWP app which has a background task and a UI.
The background task is a UWP VPN plugin. It's started when the user goes into Settings/VPN, chooses a profile and clicks on connect. At this time, Windows will start the whole app, but the UI will be hidden automatically, by Windows.
The user can then start the app, which results in Windows un-hiding the same process, showing the UI, and the user can see relevant data (this is used to show statistics etc).
The problem is, if the user then clicks on the close button, it will exit the whole process, complete with the background task.
I need a way to just put the app back into its original hidden state, as it was when it was indirectly started from Settings, and not to actually exit the process.
How can I do that in UWP?

A: This was a bug in the VPN UWP framework which was subsequently fixed in the Windows 10 Anniversary update.
Though the way the UWP VPN Framework was built, even if it closes and the process is killed, it will immediately be respawned and the connection should recover instantly.


text:
Q: Not able to interpolate I'm currently doing the codecademy introduction to javascript.
const takeOrder = (topping) => {
  console.log('Order: pizza topped with ${topping}');
};

takeOrder("mushrooms");

shouldn't this work too instead of
const takeOrder = (topping) => {
  console.log('Order: pizza topped with' +topping);
};

takeOrder("mushrooms");

I am not sure why I can not interpolate like this?

A: console.log('Order: pizza topped with ${topping}');

shouldn't this work too

No. You want backticks to use string template literals
const takeOrder = (topping) => {
  console.log(`Order: pizza topped with ${topping}`); //NB `
};

takeOrder("mushrooms");


text:
Q: How can I test if a type is safe to copy using Move I'm writing a generic vector type:
type
  TBigVector<T: record> = class
  private
    FSize: Integer;
    FEntries: TArray<T>;
    function GetEntry(Index: Integer): T;
    procedure SetEntry(Index: Integer; const Value: T);
    procedure SetSize(Value: Integer);
  public
    constructor Create(ASize: Integer);
    property Size: Integer read FSize write SetSize;
    property Entry[Index: Integer]: T read GetEntry write SetEntry; default;
    procedure Zeroise;
    function ToArray: TArray<T>;
  end;

I then want to derive classes like this:
TDoubleBigVector = class(TBigVector<Double>)
  ....
end;
TComplexBigVector = class(TBigVector<Complex>)
  ....
end;

I'm having to derive classes because I cannot implement arithmetic operations in the generic type. That is because generic constraints are not rich enough for me to constrain T to support the required arithmetic operations. Grr!
Anyway, enough of that. My question concerns the implementation of Zeroise and ToArray. For performance reasons, I want to use raw memory operations. For instance, Zeroise might be:
procedure TBigVector<T>.Zeroise;
begin
  ZeroMemory(Pointer(FEntries), Size*SizeOf(T));
end;

Now, I'm fine with doing that for types like Double and my bespoke Complex type. I know that they are not managed and a raw memory copy creates no difficulty. What I would like to do is add a runtime check, perhaps only called in my debug builds, that enforces the constraint that T has no managed types. How can I do that?

A: I would do it like this:
program SO21753006;

{$APPTYPE CONSOLE}

uses
  TypInfo,
  Windows,
  SysUtils;

type
  TProblemRecord1 = record
    I : Integer;
    S : String;
  end;

  TProblemRecord2 = record
    Obj : TObject;
  end;

  TGoodRecord = record
    I : Integer;
    K : Double;
    S : Array[0..10] of Char;
  end;

  TBigVector<T: record> = class
  private
    FSize: Integer;
    FEntries: TArray<T>;
    function GetEntry(Index: Integer): T;
    procedure SetEntry(Index: Integer; const Value: T);
    procedure SetSize(Value: Integer);
  public
    constructor Create(ASize: Integer);
    property Size: Integer read FSize write SetSize;
    property Entry[Index: Integer]: T read GetEntry write SetEntry; default;
    procedure Zeroise;
    function ToArray: TArray<T>;
  end;

function RecordHasNoManagedTypes(Typ : PTypeInfo) : Boolean;

var
 TypeData : PTypeData;

begin
 Assert(Assigned(Typ));
 Result := True;
 // only check if we have a record, or else we have a value type
 if Typ.Kind = tkRecord then
  begin
   TypeData := GetTypeData(Typ);
   Result := TypeData.ManagedFldCount = 0;
  end;
end;

{ TBigVector<T> }

constructor TBigVector<T>.Create(ASize: Integer);
begin
 Size := ASize;
end;

function TBigVector<T>.GetEntry(Index: Integer): T;
begin
end;

procedure TBigVector<T>.SetEntry(Index: Integer; const Value: T);
begin
end;

procedure TBigVector<T>.SetSize(Value: Integer);
begin
 SetLength(FEntries, Value);
end;

function TBigVector<T>.ToArray: TArray<T>;
begin
end;

procedure TBigVector<T>.Zeroise;
begin
 Assert(RecordHasNoManagedTypes(TypeInfo(T)), 'T must not have managed types!');
 ZeroMemory(Pointer(FEntries), Size*SizeOf(T));
end;

var
  Rec1 : TBigVector<Double>;
  Rec2 : TBigVector<TGoodRecord>;
  Rec3 : TBigVector<TProblemRecord1>;
  Rec4 : TBigVector<TProblemRecord2>;

begin
  try
    Writeln('Double type');
    Rec1 := TBigVector<Double>.Create(1);
    Rec1.Zeroise;
    Writeln('GoodRecord type');
    Rec2 := TBigVector<TGoodRecord>.Create(10);
    Rec2.Zeroise;
    try
     Writeln('Problemrecord1 type');
     Rec3 := TBigVector<TProblemRecord1>.Create(10);
     Rec3.Zeroise;
    except
     on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
    end;
    try
     Writeln('Problemrecord2 type');
     Rec4 := TBigVector<TProblemRecord2>.Create(10);
     Rec4.Zeroise;
    except
     on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
    end;
  except
   on E: Exception do
    Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

TObject for non-ARC platforms is not managed so the use ManagedFldCount is valid here.
UPDATE
As David pointed out, in more recent Delphi versions (Read: from D2010) you can use the Rtti.IsManaged function.
the code would look like this:
procedure TBigVector<T>.Zeroise;
begin
 Assert(not RTTI.IsManaged(TypeInfo(T)), 'T must not have managed types!');
 ZeroMemory(Pointer(FEntries), Size*SizeOf(T));
end;

UPDATE 2
From XE7 onwards you can use the intrinsic function System.IsManagedType(T). This will resolve at compile-time, incurring zero runtime overhead.
if IsManagedType(T) then Assert(false, 'T most not be a managed type');
Don't do Assert(not(IsManagedType(T)) because the compiler will not be able to remove the Assert, but it will eliminate the if if it does not apply.


text:
Q: ews GetSearchableMailboxes only return 1500 mailboxes paging I have this very simple script to get all the searchable mailboxes. I have 2000 mailboxes but this API return only 1500 every time. Wondering if the results are paged but there is no documentation regarding it.
Import-Module "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll";
$Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1);
#$Service.UseDefaultCredentials = $true;
$Service.Credentials = New-Object System.Net.NetworkCredential("test@test.com", "test123!");
$Service.Url ="https://exch2013.test.com/EWS/Exchange.asmx";
$Service;$m = $Service.GetSearchableMailboxes([string]::Empty,$false);
$count = 1;
#$m.SearchableMailboxes | %{$_.SmtpAddress; $count++;}#$count;

A: Sounds like throttling - use a paged search.
See if ECP's ediscovery search repros - if it does then its probably not an issue with your code.
There is an example of paged searches in EWSEdtior's code (you will find the code in Github).  Find the form called EDiscoverySearch.cs.  The call to GetSearchable Mailboxes does not do paging, however another piece of code in the same form does - you can adapt it for the call to GetSearchableMailboxes.


text:
Q: Implementing GraphQL (GraphQL for .Net) in ASP.NET Core, why is my Query:ObjectGraphType class not being registered by dependency injection? I've setup a basic Web Api demonstrate the use of GraphQL using ASP.Net Core. I've Followed a tutorial, what feels like exactly but am getting an error I don't understand.
I'm using GraphQL for .NET v2.4.0
This is the error:
System.InvalidOperationException: No service for type 'Land.GraphQL.Queries.LandQuery' has been registered.
  at at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
  at at GraphQL.FuncDependencyResolver.Resolve(Type type)
  at at GraphQL.FuncDependencyResolver.Resolve[T]()
  at Land.GraphQL.LandSchema..ctor(IDependencyResolver resolver) in .../LandSchema.cs:11

I'd be grateful for any light shed :)
Here's the code:
I created a LandType:ObjectGraphType to define the Type:
    public class LandType : ObjectGraphType<Entities.Land>
    {
        public LandType(ILandDataAccess landDataAccess)
        {
            Name = "Land";

            Field(land => land.Id, type: typeof(IdGraphType)).Description("Land Id in LandApi context");
            Field(land => land.Apn)
                .Description(
                    "Assessor's Parcel Number (APN) is a unique number that is assigned to each tract of land in a county by the Tax Assessor.");
            Field(land => land.Address).Description("");
            Field(land => land.ZipCode).Description("");
            Field(land => land.City).Description("");
            Field(land => land.County).Description("");
            Field(land => land.State).Description("");
            Field(land => land.Country).Description("");
            Field(land => land.GisNumber).Description("");
            Field(land => land.AssessedValue).Description("");
            Field(land => land.LegalDescription).Description("");
            Field(land => land.Acreage, type: typeof(FloatGraphType)).Description("Acreage of Land");

        }
    }

I created a LandQuery:ObjectGraphType to define the Query:
public class LandQuery : ObjectGraphType
    {
        public LandQuery(ILandDataAccess dataAccess)
        {
            Field<ListGraphType<LandType>>(
                "Land",
                resolve: context => dataAccess.GetLandsAsync());
        }
    }

I created a LandSchema:Schema to define the Schema:
public class LandSchema : Schema
    {
        public LandSchema(IDependencyResolver resolver) : base(resolver)
        {
            Query = resolver.Resolve<LandQuery>();
        }
    }

I added the service and middleware to the Startup file:
public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<IDependencyResolver>(s => new FuncDependencyResolver(
                s.GetRequiredService));

            services.AddScoped<LandSchema>();

            services.AddGraphQL(o => { o.ExposeExceptions = true; })
                .AddGraphTypes(ServiceLifetime.Scoped);
        }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
                app.UseGraphQL<LandSchema>();
        }

Edit:
Thanks to the commenters @NateBarbettini and @TonyNgo inspired me to find the answer. Turns out .AddGraphTypes only searches the calling assembly. My GraphTypes are stored in a referenced Assembly. passing the referenced assembly fixed the problem: .AddGraphTypes(typeof(LandSchema).Assembly, ServiceLifetime.Scoped);

A: I think you are missing this line of code in your ConfigureServices.
public void ConfigureServices (IServiceCollection services) {
    services.AddScoped<IDependencyResolver>(s => new FuncDependencyResolver (
        s.GetRequiredService));

    services.AddScoped<LandSchema>();
    services.AddGraphQL(x => {
            x.ExposeExceptions = true; //set true only in development mode. make it switchable.
        })
        .AddGraphTypes (ServiceLifetime.Scoped);
}

If that is not the case you can read my blog here

A: GraphQL.NET requires you to explicitly register a lot of things. Quick answer: you need to register LandQuery.
You have:
services.AddScoped<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));

The IDependencyResolver acts as a "glue" between the GraphQL.NET system (which needs to request a lot of service types) and ASP.NET Core's service collection (which contains the service types).
The object graph that you're giving to GraphQL.NET starts with LandSchema, which is correctly registered:
services.AddScoped<LandSchema>();

But look at what LandSchema is doing!
Query = resolver.Resolve<LandQuery>();

This line asks the IDependencyResolver for a LandQuery service type. Your FuncDependencyResolver is pointing at the ASP.NET Core service collection, so this will succeed if LandQuery is registered. It isn't, which is why you are getting the error

No service for type 'Land.GraphQL.Queries.LandQuery' has been registered.

To fix it, add a few new lines to ConfigureServices:
services.AddScoped<LandQuery>();
services.AddScoped<LandType>();

Any type or service (including ILandDataAccess) required by one of the GraphQL types will need to be registered in ConfigureServices. If you don't want to hand-register every single GraphQL.NET type, use Scrutor to auto-register types that derive from GraphType:
// Add all classes that represent graph types
services.Scan(scan => scan
    .FromAssemblyOf<LandQuery>()
    .AddClasses(classes => classes.AssignableTo<GraphQL.Types.GraphType>())
        .AsSelf()
        .WithSingletonLifetime());

A: EDITED:
Some months ago I created a .net core graphql project.
In the real-life, you need to tune the original library.
I want to share some tricks and common classes that help you to build a .net core graphql solution.
For example, I've created an automapper that automatically convert your dto model into a ObjectGraphType (output) and InputObjectGraphType (input).
But not only this.
For example you can't use efficiently dbcontext if you register it using AddDbContext (scoped) like a classical .net core web api, because you need to register Graphql middleware as singleton, so AddDbContext is a "fake scoped" because it is used inside a "singleton middleware".
This means that context using AddDbContext is instantiated just once at startup!
So, you will have problem of simultaneous access to the connection.
But I have solution: use factory pattern.
If you want a complete code example, see here:
https://github.com/graphql-dotnet/graphql-dotnet/issues/576#issuecomment-626661695


text:
Q: What is the difference between using __exact and Exact()? I am using Solr search for Django application using Haystack. In order to get more precise result, I had to change the search query to perform exact search -
from haystack.query import SearchQuerySet, SQ
from haystack.inputs import Exact

....
query = SQ(tags_indexed=Exact(val.lower()))
sqs = SearchQuerySet().models(
                    SampleModel).filter(query)
...

Now, other way you can do the exact search as mentioned in some documentation is -
query = SQ(tags_indexed__exact=val.lower())

What is the difference between these two?

A: SQ inherits from django's Q object and will be using djangos exact field lookup.
Exact is a Haystack class that does its own thing. (but most likely ends up at the same query)
The docs state that they are equivalent so it doesn't make much of a difference which you use.


text:
Q: Am i doing something wrong with the loops? I am using python to do some data cleaning and i've used the datetime module to split date time and tried to create another column with just the time.
My script works but it just takes the last value of the data frame.
Here is the code:
import datetime

i = 0
for index, row in df.iterrows():
    date = datetime.datetime.strptime(df.iloc[i, 0], "%Y-%m-%dT%H:%M:%SZ")
    df['minutes'] = date.minute
    i = i + 1

This is the dataframe  :
Output

A: df['minutes'] = date.minute reassigns the entire 'minutes' column with the scalar value date.minute from the last iteration.
You don't need a loop, as 99% of the cases when using pandas.
You can use vectorized assignment, just replace 'source_column_name' with the name of the column with the source data.
df['minutes'] = pd.to_datetime(df['source_column_name'], format='%Y-%m-%dT%H:%M:%SZ').dt.minute

It is also most likely that you won't need to specify format as pd.to_datetime is fairly smart.
Quick example:
df = pd.DataFrame({'a': ['2020.1.13', '2019.1.13']})
df['year'] = pd.to_datetime(df['a']).dt.year
print(df)

outputs
           a  year
0  2020.1.13  2020
1  2019.1.13  2019

A: Seems like you're trying to get the time column from the datetime which is in string format. That's what I understood from your post.
Could you give this a shot?
from datetime import datetime
import pandas as pd

def get_time(date_cell):
    dt = datetime.strptime(date_cell, "%Y-%m-%dT%H:%M:%SZ")
    return datetime.strftime(dt, "%H:%M:%SZ")

df['time'] = df['date_time'].apply(get_time)


text:
Q: Apple Memo recorder - Container & Elevated button or Container same size, can't do like apple memo recorder view I am trying to duplicate the Apple memo record interface, but I have an issue with the container. I have tried to use an other container & also elevated button but in both cases, the widget have the same size. I do not understand why.

Container _RecordButton(){

    return Container(
        height: 90,
        width: 90,
        decoration: BoxDecoration(
          border: Border.all(
            width: 4.0,
            color: Colors.grey,
          ),
          shape: BoxShape.circle,
        ),
      child: Container(

          child: _createElevatedButton()),);  //_RecordButton2()
  }

  Container _RecordButton2(){

    return Container(
          height: 15,
          width: 15,
      color: Colors.red,
    );
  }

  ElevatedButton _createElevatedButton(
      {IconData icon,  Function onPressFunc}) {
    return ElevatedButton(
        onPressed: () {},
        style: ButtonStyle(
        shape: MaterialStateProperty.all(CircleBorder()),
        padding: MaterialStateProperty.all(EdgeInsets.all(20)),
        backgroundColor: MaterialStateProperty.all(Colors.red), // <-- Button color

           ));

A: it is so simple that I should have find it before. Here is the answer, it might help someone else.
Container _RecordButton(){

    return Container(
        height: 90,
        width: 90,
        decoration: BoxDecoration(
          border: Border.all(
            width: 4.0,
            color: Colors.grey,
          ),
          shape: BoxShape.circle,
        ),
      child: Padding(
          padding: EdgeInsets.all(4.0),
          child: _createElevatedButton()),);  //_RecordButton2()
  }


text:
Q: Одна колонка сильно больше остальных в графике Одна колонка сильно длиннее остальных.
Можно ли каким либо способом её обрезать средствами highcharts (вставить многоточие например)?

A: Нашел решение. называется breaks. Добавляется в yAxis и xAxis.
Еще надо подключить файл с этим модулем, иначе работать не будет.
Чтобы был виден разрыв столбца, используется специальная функция pointBreakColumn которую можно найти в примере.
yAxis: {
           breaks: [{
                from: 200,
                to: 1500,
           }]
}

Пример:
http://jsfiddle.net/ppotaczek/txof86a4/1/
Доки:
https://api.highcharts.com/highcharts/yAxis.breaks


text:
Q: Resource id in admin directory api Hello can some one please tell me what is resource id in below image?
enter image description here

A: From Retrieve a mobile device docs:

The resourceId is a unique Google identifier for a device and is found
  in the response of the Retrieve all mobile devices
  method.


text:
Q: How does Gnome (Cinnamon) find the icon for an executable binary? I recently installed the Chromium-webbrowser under Linux-Mint 18 with the apt-package manager.
Later I downloaded a 64bit Chromium-build for linux in a .zip-file. After I executed the containing binary "chrome", I recognized that the tray-icon is exactly the same icon used by my current theme for Chromium. So I tried to change the icon with the following .desktop-file:
[Desktop Entry]
Type=Application
Name=Chrome
Exec=MY/LOCAL/PATH/chrome
Icon=MY/LOCAL/PATH/testIcon.png
Terminal=false

The icon of the .desktop-file changed, but as I started the application I noticed that the tray-icon from the theme is used, instead of my desired icon.
How can this be? When I usually start a downloaded executable file a "default"-icon from the installed theme is used. How does the icon for the binary get found?
How can I use a custom tray-icon for my downloaded binary?
Thank you!


text:
Q: How to get webpack to export a dependency as separate file? I have a webpack/React project that builds fine and creates a minified and bundled file in dist/file.min.js.  However, I would also like one of the javascript files for a dependency I specify with yarn (but never use in this code) to appear in that output dist folder as well.
In particular, I've used yarn to specify that the lz-string library is a project dependency:
{"dependencies": {"lz-string": "^1.4.4"}}
And would like to have webpack export lz-string.min.js to the dist folder as well.  In short, how do I get the following output?
/dist/
   file.min.js
   lz-string.min.js

If lz-string isn't used anywhere in the javascript in this code?  (I just want to copy the version I have specified in yarn to the same output folder using webpack).

A: You can use the CopyWebpackPlugin to do this.
Add copy plugin: yarn add copy-webpack-plugin --dev.  Then modify your webpack.config.js by adding these lines:
const CopyWebpackPlugin = require('copy-webpack-plugin');

config.plugins.push(new CopyWebpackPlugin([
    {from: 'node_modules/lz-string/lz-string.min.js', to: ''}
]))


text:
Q: Is there a name for this type of socket connection status scenario? I'm running a simple client/server on the same (windows) computer. The server listens on port 9878. Here is the connection status of the server exe, as captured by Process Explorer:
Protocol    Localhost         Remote            Status
TCP         localhost:9878   localhost:0        LISTENING
TCP         localhost:9878   localhost:55555    ESTABLISHED
TCP         localhost:55555  localhost:9878     ESTABLISHED

As you can see something has gone wrong. The problem i observe is that data is sent infinitely from server to client now.  Is there a name for such a situation seen here where the server is connected on 2 ports to the same machine?  Also, is there a typical way in which this might happen?  For me, it happens as soon as the client disconnects after the first connection.

A: There is nothing wrong with that listing.  That is exactly the set of connections you should see when a local client connects to a local server.  You do have three sockets in this scenario:

*

*Server - listening socket

*Server - connected socket to client

*Client  - connected socket to server

If you are having some sort of issue it is probably a bug in your code.


text:
Q: Does Adobe Air support KEEP ALIVEs / persistent HTTP connections As far as I can tell Adobe Air does not support persistent HTTP connections via KEEP ALIVEs.
Does anyone know any different?
Thanks

A: Adobe Air runs on Webkit, so you can use the Web Sockets API.

A: I'm currently building an application that connects to a Comet-style long-poll API. To keep connections open, just make sure to set URLRequestDefaults.idleTimeout to some sensible value (the default varies from system to system but is probably around 30 seconds). I am successfully keeping connections open for 15 minutes at a time. You may also need to add a Connection: Keep-Alive header like so:
myRequest.requestHeaders.push( new URLRequestHeader("Connection", "Keep-Alive"));


text: Q: Torus as example of supermanifold Where can I find examples of supermanifold? In particular "supertorus". I am interested in the complex differential forms expressed on such geometries, and moreover I would like to know if hodge numbers for complex supermanifolds can be computed. Some reference would be of a great help


text:
Q: How to select an exact string in XSLT I need to select a string with an exact value of "RM" in my XML document.
Here is a sample of my document. Note that the structure and values of other nodes are not permanent, so I cannot use a relative location to aid me.
?xml version="1.0" encoding="UTF-16"?>
<?xml-stylesheet type="text/xsl" href="XSLT.xsl"?>
<document xmlns="http://www.scansoft.com/omnipage/xml/ssdoc-schema3.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <page ocr-vers="OmniPageCSDK18" app-vers="OmniPage 19">
        <description>
            <source file="C:\Users\User\Documents\OCR\Unprocessed\7740412639.pdf" dpix="300" dpiy="300" sizex="2480" sizey="3509"/>
            <theoreticalPage size="A4" marginLeft="1440" marginTop="0" marginRight="1440" marginBottom="1440" offsetX="-2" offsetY="-2" width="11918" height="16854"/>
        </description>

                    <picture l="115" t="322" r="9667" b="16536" alignment="left">
                    </picture>

                    <para l="7234" t="1171" r="7334" b="1392" alignment="left" spaceBefore="29" spaceAfter="24" lsp="exactly" lspExact="100" language="en">
                        <ln l="7234" t="1171" r="7334" b="1392" baseLine="1319" underlined="none" subsuperscript="none" fontSize="700" fontFace="Times New Roman" fontFamily="roman" fontPitch="variable" spacing="-40">
                            <wd l="7234" t="1171" r="7334" b="1392">ARMARMRM</wd>
                        </ln>
                    </para>

                    <para l="6888" t="1118" r="6989" b="1426" alignment="left" spaceBefore="29" spaceAfter="23" lsp="exactly" lspExact="101" language="en">
                        <ln l="6888" t="1118" r="6989" b="1426" baseLine="1307" underlined="none" subsuperscript="none" fontSize="700" fontFace="Times New Roman" fontFamily="roman" fontPitch="variable" spacing="-31">
                            <wd l="6888" t="1118" r="6989" b="1426">RM</wd>
                        </ln>
                    </para>

    </page>
</document>

I have tried using contains and ensuring that the value is NaN. I've also researched about using matches and have had a look at regex, though this is apparently only available in a XSLT 2.
Is there actually a way to do this in XSLT? If so, how?
Clarification
When I say
Note that the structure and values of other nodes are not permanent I mean that you cannot use an Xpath to navigate to a node, since that Xpath can change.

A: The following selects the string that contains only the letters "RM":
//ss:wd[. = 'RM']


text:
Q: Conditional SUM in a SQL query SELECT
    CustomerCode,
    CustomerName,
    LocationCode,
    LocationName,
    ProductCode,
    ProductDesc,
    CONVERT(DATE, OrderDate) As OrderDate,
    **SUM(NoOfCube) PlantCube,**  <---- i want to set value if CubeAtPlant =1
    **SUM(NoOfCube) SiteCube,**   <---- i want to set value if CubeAtPlant =0
    ShortPlantName,
    OrderNo,
    slumpReqType,
    slumpReqFreeText,
    cubeReqType,
    cubeReqFreeText
FROM
    (SELECT
        ROW_NUMBER() OVER(PARTITION BY OH.OrderNo ORDER BY OD.ActualStartTime ASC) AS Row,
        CustomerCode,
        CustomerName,
        LocationCode,
        LocationName,
        OD.ProductCode,
        OD.ProductDesc,
        CONVERT(DATE, OrderDate) As OrderDate,
        NoOfCube,
        NoOfCube SiteC,
        PLT.ShortPlantName,
        PLT.PlantCode,
        OH.OrderNo,
        slumpReqType,
            slumpReqFreeText,
            cubeReqType,
            cubeReqFreeText
    FROM
        OrderHeader OH
        INNER JOIN OrderDetail OD ON OH.OrderNo = OD.OrderNo AND OD.DONo IS NOT NULL
        INNER JOIN EmailReportPlantList PLT ON OD.ActualBatchingPlant = PLT.PlantCode
    WHERE 1=1
        **AND NoOfCube > 0 AND CubeAtPlant = 1**----If it is then set value in PlantCube

         AND NoOfCube > 0 AND CubeAtPlant = 0   ----If it is then set value in SiteCube

    ) A
WHERE Row = 1

    AND (CustomerCode = '' )
    AND (PlantCode in (''))
    AND OrderDate Between '' AND ''
GROUP BY
    CustomerCode,
    CustomerName,
    LocationCode,
    LocationName,
    ProductCode,
    ProductDesc,
    CONVERT(DATE, OrderDate),
    ShortPlantName,
    OrderNo,
    slumpReqType,
    slumpReqFreeText,
    cubeReqType,
    cubeReqFreeText
ORDER BY
    CustomerCode,
    CustomerName,
    LocationCode,
    LocationName,
    ProductCode,
    ProductDesc,
    CONVERT(DATE, OrderDate),
    ShortPlantName,
    OrderNo

Kindly help me to write correct query.

A: You can use CASE of IF to do conditional sums, if the condition is true add the amount to the total, if it is false add zero.
SELECT
  ...
  SUM(CASE WHEN CubeAtPlant = 1 THEN NoOfCube ELSE 0 END) AS PlantCube,
  SUM(CASE WHEN CubeAtPlant = 0 THEN NoOfCube ELSE 0 END) AS SiteCube,
  ...

I'm not sure what you are trying to do in the WHERE clause:
WHERE 1=1
  AND NoOfCube > 0 AND CubeAtPlant = 1
  AND NoOfCube > 0 AND CubeAtPlant = 0
...

I assume CubeAtPlant can only be 1 or 0, in which case you can just have
WHERE 1=1
  AND NoOfCube > 0
...

Update your question or comment on this answer if that is not the case.


text:
Q: Django Channels - correct way to reject an unauthorized websocket request? I have a AsyncWebSocketConsumer which first authorizes a user's credential cookies before accepting their connection, as so:
// consumer.py

class AuthWebSocketConsumer(AsyncWebSocketConsumer):

    async def connect(self):

        if not(await self.authorized(self.scope)):
            await self.close(code=4004)
        else:
            await self.accept()

However, on the client side, I am seeing this as an onerror event followed by an onclose event with a Websocket code of 1006, not 4004 as I sent back.
// socket.js

this.log_socket = new WebSocket(url.href);

this.log_socket.onerror = (event) => {
  // Happens on Websocket REJECTs
  console.log("Socket error", event);
};

this.log_socket.onclose = (event) => {
  console.log("Socket closed: ", event);
};

The logged close event being as so
CloseEvent {isTrusted: true, wasClean: false, code: 1006, reason: "", type: "close", …}
bubbles: false
cancelBubble: false
cancelable: false
code: 1006

It seems either Django channels is not forwarding the websocket close code, or the browser is masking the error code as the connection was never accepted. In which case, what is the proper way to relay to the client that they are not authenticated for Websocket connects (or some other rejection reason)? It seems at the moment, I need to accept the connection before immediately closing it - which seems a little bit like a security flaw?

A: I had the same problem once and solved it like follows:
// consumer.py

class AuthWebSocketConsumer(AsyncWebSocketConsumer):

    async def connect(self):
        await self.accept()
        if not(await self.authorized(self.scope)):
            await self.close(code=4004)

I saw someone's comment on stackoverflow. It said that you need to accept the connection first to send the close code. Unfortunately I wasn't able to find the original comment.


text:
Q: Situations in which to express integration constant as its natural log What is the complete reasoning behind constants of integration, specifically in the case of the natural log?
Given $\int\left(\frac{1}{250-x}\right)dx=\int(dt)$ (1), I obtain:
$\ln\left(\frac{1}{250-x}\right)=t+C$
My textbook gives the solution for this problem as:
$\ln\left(\frac{1}{250-x}\right)=t+\ln(C)$
However, for another basic problem, we do not end up taking the natural log of the constant of integration:
$\int\left(\frac{1}{x(1-x)}\right)dx=\int(dt)$ (2)
The text finds:
$\ln\left(\frac{x}{x-1}\right)=t+C$
Why is the constant of integration expressed as its natural log in the case of 1, but not in the case of 2?

A: It depends upon the context of the problem.
In your first example it appears that perhaps one intends to solve for $x$ but in the second example it appears than one does not intend to solve for $x$. In the first example one immediately obtains
\begin{equation}
\frac{1}{250-x}=Ce^t
\end{equation}
by having expressed the constant in the form $\ln C$. If one wished to solve the second example for $x$ it would be better to use $\ln C$ there as well.


text:
Q: Classifying plane regions by their fundamental groups The Riemann mapping theorem in complex analysis implies that any two simply connected open subsets of $\mathbb C$ are homeomorphic.
Does anybody know if there is a more general theorem along the lines of: "Two connected open subsets of $\mathbb C$ are homeomorphic iff they have the same fundamental groups"?
I have never seen this written down, and yet, it is very difficult to come up with a counterexample. The examples I'm coming up with all look like an annulus with multiple holes - for these examples, the statement is obviously true.

A: This is false. Consider $S=R^2 - {\mathbb Z}\times \{0\}$ as one surface; as the other surface consider $S - \{\frac{1}{n}: n\in {\mathbb N}\}$. Both surfaces have free groups of countably infinite rank, but they are not homeomorphic. (To prove the latter you need the theory of ends. You can also take a look at the references here). On the other hand, if you consider only domains in $R^2$ with finitely generated fundamental groups then indeed the fundamental group (or even just the 1st Betti number) determines the surface up to homeomorphism.


text:
Q: xfce4-terminal annoying bottom and right border I've just encountered an annoying visual problem - there is a pretty thick bottom and thin right border in xfce4-terminal. I guess I didn't notice it before because I was using visually non-enchanted editors before. The problem can be clearly seen when, for example, using vim themes. It is not so oblivious when using out-of-the-box nano but the border / margin is still there.
Is there a way to remove the border?
A related screenshot (teal bottom and right border)

A: Had the same issue just today. Happens only when I maximize the terminal window. "Solved" it by just setting my terminal background color the same as the one from my vim theme...
See Reddit Thread:

Vim can only paint the background by printing characters which is why it can't change the color of the left over space - it's too short to fit any characters.

I still dont get why it only happens in fullscreen and not like every 9 of 10 pixels, though.
I'm stupid; This is because the terminal app does not resize per pixel but per character. So of course manual resizing never brings a border.
But this also means, you could simply fix this problem by choosing a bigger/smaller font in your terminal app, where your screen resolution is a real multiple of the character width.
Also:

Try this in your vimrc after your theme is loaded, works for jellybean at least:

hi Normal ctermbg=none

Might make some other trouble, but you could give it a try.


text:
Q: Postgresql error: insert operation returns id exists in Python I tried to insert name into database.
name = 'test'
cur.execute("INSERT INTO scholars(name) VALUES('{}') returning id".format(name))
id = cur.fetchone()
print(id)

error message:
psycopg2.IntegrityError: duplicate key value violates unique constraint "idx_16514_primary"
DETAIL:  Key (id)=(2321) already exists.

When id=2301, it succeed,and return ID.
After that,id += 1and returns the error below.
http://ob9j09f06.bkt.clouddn.com/2016-10-12-16%3A31%3A12.jpg

A: Seems to me that You already have record with ID 2321 in your DB. Can You check with SELECT id FROM scholars?

A: Thanks @e4c5, @kxxoling
Here i got the answer How to reset postgres' primary key sequence when it falls out of sync? to this question.
Something was wrong with my id sequence.
I fixed it by doing this.
SELECT MAX(id) FROM scholars;

=> 11518
SELECT nextval('scholars_id_seq');

=> 2324 # here it is lower than max(id)
SELECT setval('scholars_id_seq', (SELECT MAX(id) FROM scholars));

=> 11518 # fix it
SELECT nextval('scholars_id_seq');

=> 11519 # normal


text:
Q: How do I prevent errors about trying to present a controller on a controller which is already presenting? Once in a while, I get errors like:
Warning: Attempt to present <Controller3>  on <Controller1> which is already presenting <Controller2>

I understand that the next controller needs to be presented on the controller that's at the top of the stack (Controller2), not a controller somewhere below (Controller1).
Instead of fixing such errors one-off, how do we design our app to prevent this problem once and for all?

A: One clean solution to this problem is a navigation controller.
If you can't or don't want to use one, you can easily simulate it on a normal view controller:
extension UIViewController {
  var topViewController: UIViewController {
    return presentedViewController == nil ? self : presentedViewController!.topViewController
  }

  // If the topmost view controller is an instance of one of the given classes, it's popped.
  // Then, the given view controller, if any, if pushed.
  //
  // This function can be called on any of the view controllers in the stack.
  func pop(ifOneOf: [AnyClass], thenPush: UIViewController? = nil) {
    if topViewController.presentingViewController != nil && topViewController.isKindOfOneOf(ifOneOf) {
      topViewController.dismiss(animated: false, completion: {
        self.pop(ifOneOf: [], thenPush: thenPush)
      })
      return
    }
    if thenPush != nil {
      push(thenPush!)
    }
  }

  // Pushes the given view controller onto the stack.
  //
  // This method can be called on any of the view controllers in the stack.
  func push(_ child: UIViewController) {
    topViewController.present(child, animated: true)
  }
}

extension NSObjectProtocol {
  func isKindOfOneOf(_ classes: [AnyClass]) -> Bool {
    for clazz in classes {
      if isKind(of: clazz) {
        return true
      }
    }
    return false
  }
}

As you can see, this provides push() and pop(), similar to a navigation controller. Further, you can call these methods on any controller in the stack, and it will automatically redirect them to the topmost controller, preventing the error in the question.
This extension also fixes the problem that if you want to dismiss a controller and present another, you need to present only in the completion block, even if you're dismissing without an animation. Otherwise, you'll get the same error as above. This extension fixes all these problems.


text:
Q: Is there an alternative for `proxy_options` now that it's been removed? rails In rails 2 you could use proxy_options to see the options for specific database queries. In rails 3 it has been removed. Is there a different option for getting this same info?

A: I posted a long answer here: How to test a scope in Rails 3
But the main answer is use #where_values_hash or #to_sql on your scope.

A: I only now learned of a nicer way. Undocumented but nice:
User.joins(:address).merge(Address.foreign)

as an alternative to
User.joins(:address).where(Address.foreign.where_values)


text:
Q: gtest - linker finds `libgtest.a` but still complains undefined reference to `testing::Test::Test()` I am new to google test for C++.
I installed google test by downloading source code from GitHub.
I built it with CMake and installed it into $HOME/.local.
Then I test with the following code.
#include "gtest/gtest.h"

TEST(Foo, Bar) {
  EXPECT_TRUE(true);
}

I compiled it with
clang++ -std=c++1z -I$HOME/.local/include -L$HOME/.local/lib -lgtest -lgtest_main a.cc
which gives the following linker errors
/tmp/a-dc64ec.o: In function `Foo_Bar_Test::TestBody()':
a.cc:(.text+0x5f): undefined reference to `testing::Message::Message()'
a.cc:(.text+0x81): undefined reference to `testing::internal::GetBoolAssertionFailureMessage[abi:cxx11](testing::AssertionResult const&, char const*, char const*, char const*)'
a.cc:(.text+0xaa): undefined reference to `testing::internal::AssertHelper::AssertHelper(testing::TestPartResult::Type, char const*, int, char const*)'
a.cc:(.text+0xbc): undefined reference to `testing::internal::AssertHelper::operator=(testing::Message const&) const'
a.cc:(.text+0xca): undefined reference to `testing::internal::AssertHelper::~AssertHelper()'
a.cc:(.text+0x109): undefined reference to `testing::internal::AssertHelper::~AssertHelper()'
/tmp/a-dc64ec.o: In function `__cxx_global_var_init.1':
a.cc:(.text.startup+0x8a): undefined reference to `testing::internal::GetTestTypeId()'
a.cc:(.text.startup+0x134): undefined reference to `testing::internal::MakeAndRegisterTestInfo(char const*, char const*, char const*, char const*, testing::internal::CodeLocation, void const*, void (*)(), void (*)(), testing::internal::TestFactoryBase*)'
/tmp/a-dc64ec.o: In function `testing::internal::SuiteApiResolver<testing::Test>::GetSetUpCaseOrSuite(char const*, int)':
a.cc:(.text._ZN7testing8internal16SuiteApiResolverINS_4TestEE19GetSetUpCaseOrSuiteEPKci[_ZN7testing8internal16SuiteApiResolverINS_4TestEE19GetSetUpCaseOrSuiteEPKci]+0x6a): undefined reference to `testing::internal::IsTrue(bool)'
a.cc:(.text._ZN7testing8internal16SuiteApiResolverINS_4TestEE19GetSetUpCaseOrSuiteEPKci[_ZN7testing8internal16SuiteApiResolverINS_4TestEE19GetSetUpCaseOrSuiteEPKci]+0x9b): undefined reference to `testing::internal::GTestLog::GTestLog(testing::internal::GTestLogSeverity, char const*, int)'
a.cc:(.text._ZN7testing8internal16SuiteApiResolverINS_4TestEE19GetSetUpCaseOrSuiteEPKci[_ZN7testing8internal16SuiteApiResolverINS_4TestEE19GetSetUpCaseOrSuiteEPKci]+0x122): undefined reference to `testing::internal::GTestLog::~GTestLog()'
a.cc:(.text._ZN7testing8internal16SuiteApiResolverINS_4TestEE19GetSetUpCaseOrSuiteEPKci[_ZN7testing8internal16SuiteApiResolverINS_4TestEE19GetSetUpCaseOrSuiteEPKci]+0x137): undefined reference to `testing::internal::GTestLog::~GTestLog()'
/tmp/a-dc64ec.o: In function `testing::internal::SuiteApiResolver<testing::Test>::GetTearDownCaseOrSuite(char const*, int)':
a.cc:(.text._ZN7testing8internal16SuiteApiResolverINS_4TestEE22GetTearDownCaseOrSuiteEPKci[_ZN7testing8internal16SuiteApiResolverINS_4TestEE22GetTearDownCaseOrSuiteEPKci]+0x6a): undefined reference to `testing::internal::IsTrue(bool)'
a.cc:(.text._ZN7testing8internal16SuiteApiResolverINS_4TestEE22GetTearDownCaseOrSuiteEPKci[_ZN7testing8internal16SuiteApiResolverINS_4TestEE22GetTearDownCaseOrSuiteEPKci]+0x9b): undefined reference to `testing::internal::GTestLog::GTestLog(testing::internal::GTestLogSeverity, char const*, int)'
a.cc:(.text._ZN7testing8internal16SuiteApiResolverINS_4TestEE22GetTearDownCaseOrSuiteEPKci[_ZN7testing8internal16SuiteApiResolverINS_4TestEE22GetTearDownCaseOrSuiteEPKci]+0x118): undefined reference to `testing::internal::GTestLog::~GTestLog()'
a.cc:(.text._ZN7testing8internal16SuiteApiResolverINS_4TestEE22GetTearDownCaseOrSuiteEPKci[_ZN7testing8internal16SuiteApiResolverINS_4TestEE22GetTearDownCaseOrSuiteEPKci]+0x12d): undefined reference to `testing::internal::GTestLog::~GTestLog()'
/tmp/a-dc64ec.o: In function `Foo_Bar_Test::~Foo_Bar_Test()':
a.cc:(.text._ZN12Foo_Bar_TestD2Ev[_ZN12Foo_Bar_TestD2Ev]+0x14): undefined reference to `testing::Test::~Test()'
/tmp/a-dc64ec.o: In function `Foo_Bar_Test::Foo_Bar_Test()':
a.cc:(.text._ZN12Foo_Bar_TestC2Ev[_ZN12Foo_Bar_TestC2Ev]+0x1b): undefined reference to `testing::Test::Test()'
/tmp/a-dc64ec.o:(.rodata+0x20): undefined reference to `testing::Test::SetUp()'
/tmp/a-dc64ec.o:(.rodata+0x28): undefined reference to `testing::Test::TearDown()'
/tmp/a-dc64ec.o:(.rodata+0x60): undefined reference to `typeinfo for testing::Test'
/home/wyq/.local/lib/libgtest_main.a(gtest_main.cc.o): In function `main':
gtest_main.cc:(.text+0x32): undefined reference to `testing::InitGoogleTest(int*, char**)'
/home/wyq/.local/lib/libgtest_main.a(gtest_main.cc.o): In function `RUN_ALL_TESTS()':
gtest_main.cc:(.text._Z13RUN_ALL_TESTSv[_Z13RUN_ALL_TESTSv]+0x5): undefined reference to `testing::UnitTest::GetInstance()'
gtest_main.cc:(.text._Z13RUN_ALL_TESTSv[_Z13RUN_ALL_TESTSv]+0xd): undefined reference to `testing::UnitTest::Run()'
clang-12: error: linker command failed with exit code 1 (use -v to see invocation)

Adding --verbose to clang gives the following linker command
"/usr/bin/ld" -z relro --hash-style=gnu --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o a.out /usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/crt1.o /usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/5.4.0/crtbegin.o -L/home/wyq/.local/lib -L/usr/lib/gcc/x86_64-linux-gnu/5.4.0 -L/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu -L/lib/x86_64-linux-gnu -L/lib/../lib64 -L/usr/lib/x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../.. -L/home/wyq/.local/bin/../lib -L/lib -L/usr/lib -lgtest -lgtest_main a.o -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/5.4.0/crtend.o /usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/crtn.o

Adding --verbose to ld shows that it actually finds libgtest.a and libgtest_main.a.
"/usr/bin/ld" -z relro --hash-style=gnu --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o a.out /usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/crt1.o /usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/5.4.0/crtbegin.o -L/home/wyq/.local/lib -L/usr/lib/gcc/x86_64-linux-gnu/5.4.0 -L/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu -L/lib/x86_64-linux-gnu -L/lib/../lib64 -L/usr/lib/x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../.. -L/home/wyq/.local/bin/../lib -L/lib -L/usr/lib -lgtest -lgtest_main a.o -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/5.4.0/crtend.o /usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/crtn.o --verbose 2>&1 | grep gtest

attempt to open /home/wyq/.local/lib/libgtest.so failed
attempt to open /home/wyq/.local/lib/libgtest.a succeeded
attempt to open /home/wyq/.local/lib/libgtest_main.so failed
attempt to open /home/wyq/.local/lib/libgtest_main.a succeeded
(/home/wyq/.local/lib/libgtest_main.a)gtest_main.cc.o
/home/wyq/.local/lib/libgtest_main.a(gtest_main.cc.o): In function `main':
gtest_main.cc:(.text+0x32): undefined reference to `testing::InitGoogleTest(int*, char**)'
/home/wyq/.local/lib/libgtest_main.a(gtest_main.cc.o): In function `RUN_ALL_TESTS()':
gtest_main.cc:(.text._Z13RUN_ALL_TESTSv[_Z13RUN_ALL_TESTSv]+0x5): undefined reference to `testing::UnitTest::GetInstance()'
gtest_main.cc:(.text._Z13RUN_ALL_TESTSv[_Z13RUN_ALL_TESTSv]+0xd): undefined reference to `testing::UnitTest::Run()'

Why is this? How can I correctly link gtest libraries?

A: Wrong order for linker arguments
a.cc -lgtest -lgtest_main

not
-lgtest -lgtest_main a.cc


text:
Q: How to move files WHILE creating their folders. Directory.Method, etc
I've found a python post on this but couldn't "convert" it...

So I already have this:
    if (Directory.GetFiles(sourcePath, "*_Items_*.pdf").Any())
    {
        string[] pdfFiles = Directory.GetFiles(sourcePath, "*_Items_*.pdf");
        foreach (string path in pdfFiles)
        {
            file = Path.GetFileName(path);
            subString = file.Substring(0, 8);
            Directory.CreateDirectory(Path.Combine(targetPath, subString));
        }
    }

So in the code I take letters out of files and create folders with those substrings. How would I also move these files directly to their folder created with their substring?
If else because I make a message that says "No items list found" when there are no files.
Every help appreciated, thanks.

A: I'd imagine you can simply use File.Move to move the file.
foreach (string path in pdfFiles)
{
    file = Path.GetFileName(path);
    subString = file.Substring(0, 8);
    var targetFolder = Path.Combine(targetPath, subString);
    Directory.CreateDirectory(targetFolder);
    // Move the file into the created folder
    File.Move(path, Path.Combine(targetFolder, file));
}

A: There are 2 methods FileInfo.MoveTo() vs File.Move() to use.
The code can be like with the help of LINQ : Create a directory for each file after a check if the folder exists already.
Then move to the new folder created
var files = Directory.GetFiles(sourcePath, "*_Items_*.pdf").ToList();

files.ForEach(f => {
    var fileInfo = new FileInfo(f);
    var pathName= fileInfo.Name.Substring(0, 8);

    var directoryInfo = new DirectoryInfo(Path.Combine(targetPath, pathName));
    if(!directoryInfo.Exists)
       directoryInfo.Create();

    fileInfo.MoveTo(Path.Combine(directoryInfo.FullName, fileInfo.Name); // think about if file already exist

})


text:
Q: valgrind shows me a leak when using libxml2 i have a code which i must fix it. It has a leak, I don't know where is the problem, but i think something is bad done.
is there anybody who has the same problem and can help me please?
==3923== 32 bytes in 1 blocks are still reachable in loss record 1 of 2
==3923==    at 0x4C2CC70: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3923==    by 0x652168F: _dlerror_run (dlerror.c:141)
==3923==    by 0x65210C0: dlopen@@GLIBC_2.2.5 (dlopen.c:87)
==3923==    by 0x693F475: ??? (in /lib/x86_64-linux-gnu/liblzma.so.5.0.0)
==3923==    by 0x6943DC7: lzma_auto_decoder (in /lib/x86_64-linux-gnu/liblzma.so.5.0.0)
==3923==    by 0x5DB14DC: ??? (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1)
==3923==    by 0x5DB1E4F: __libxml2_xzread (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1)
==3923==    by 0x5CFFB08: ??? (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1)
==3923==    by 0x5D01674: xmlParserInputBufferGrow (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1)
==3923==    by 0x5CD3E34: xmlParserInputGrow (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1)
==3923==    by 0x5CD921A: ??? (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1)
==3923==    by 0x5CEB03C: xmlParseDocument (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1)
==3923==
==3923== 44 bytes in 1 blocks are still reachable in loss record 2 of 2
==3923==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3923==    by 0x400FDC0: _dl_signal_error (dl-error.c:90)
==3923==    by 0x40146CF: _dl_open (dl-open.c:715)
==3923==    by 0x652102A: dlopen_doit (dlopen.c:66)
==3923==    by 0x400FFF3: _dl_catch_error (dl-error.c:187)
==3923==    by 0x652162C: _dlerror_run (dlerror.c:163)
==3923==    by 0x65210C0: dlopen@@GLIBC_2.2.5 (dlopen.c:87)
==3923==    by 0x693F475: ??? (in /lib/x86_64-linux-gnu/liblzma.so.5.0.0)
==3923==    by 0x6943DC7: lzma_auto_decoder (in /lib/x86_64-linux-gnu/liblzma.so.5.0.0)
==3923==    by 0x5DB14DC: ??? (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1)
==3923==    by 0x5DB1E4F: __libxml2_xzread (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1)
==3923==    by 0x5CFFB08: ??? (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1)
==3923==
==3923== LEAK SUMMARY:
==3923==    definitely lost: 0 bytes in 0 blocks
==3923==    indirectly lost: 0 bytes in 0 blocks
==3923==      possibly lost: 0 bytes in 0 blocks
==3923==    still reachable: 76 bytes in 2 blocks
==3923==         suppressed: 0 bytes in 0 blocks

A: http://valgrind.org/docs/manual/faq.html

"still reachable" means your program is probably ok -- it didn't free some memory it could have. This is quite common and often reasonable. Don't use --show-reachable=yes if you don't want to see these reports.

As said, your code should be alright. :)


text:
Q: How to pass data between activities forward and backward, android, kotlin Let's say my application has 4 activities (A -> B -> C -> D) when going forward, activity A pass a data value called category to activity B and then activity B pass category and also and data value called level and both used in activity D to get data from firebase realtime database. but when the user goes back to activity C and tries to go again to D data passed from A (category) is now null. so data can't retrieve from firebase. my question is how can I solve this situation.? "I pass data using Intent by putting extras." are there any other ways?

A: you could use startactivityforresult and set a result intent which includes the data you want to pass back
https://developer.android.com/training/basics/intents/result

A: You can use a shared ViewModel. Viewmodels are lifecycle-aware components. Data in ViewModels does not disappear when activity changes
Save your data (category,level) in ViewModel like this :
private val _categoryValue =
    MutableLiveData<CategoryType>()
val categoryValue:
LiveData<ResponseState<CategoryType> =
    _categoryValue

And update your data in activity like this:
vm.categoryValue.value = newCategoryValue

If you are using binding etc. observe and do stuff with your data like this:
vm.deleteFileResponse.observe(this){ category ->
  //Do stuff
 }


text:
Q: Can I install a PC-MAC DVD Rom application on Ubuntu 12.04LTS? I bought by mistake a collection of sceneries for XPlane (Fligh Sim) but I didn't realise these DVDs are for PC and Mac only. Is there a way to install them on Ubuntu anyway? Thanks for your patience, I am a noobie ;-)

A: Try to install it with wine:
https://help.ubuntu.com/community/Wine
It can run Windows software on linux, but it doesen't work with all software.
Give it a try and report any problems, maybe someone can help.


text:
Q: How to determine the best location (country) for an email server? Is there any advantage to have an email server in the same country as the email account holders?
Example:
All emails are from people of country A. They send and receive emails mainly from/to country A.
Is there any difference to have an email server in Country A with ping < 20ms or in Country B with ping < 75ms.
Both are in Europe and use cpanel/whm.

A: The main reason to have a mail server in the same country should be to have it under the same applicable local laws.
Apart from that latency is not important for e-mails.

A: The longer the distance, the longer it will take to retrieve the email....afterall the amount of hardware increases and the bandwidth between two underlying internal connections can well have a dramatic effect.

A: Unless account holders on the mailserver, and recipients are in the same local network, the traffic will head out to the internet anyway, so you won't see much bandwidth savings.  Remember what sysadmins always say:  Mail Is Not an Instant Messaging Protocol ;)  Besides, the difference in ping times you reference are likely minimal compared to the time spent filtering the messages for spam.


text:
Q: Processing a buttonclick in Oracle forms programticly for an implementation class I am having the following problem which is exclusive to the oracle forms framework and custom implementation classes provided in java. I modified a VButton to display a custom menue as soon as i am pressing the right mouse button.
The following was accomplished by inheriting from the VButton and providing a custom behavior.
The popup will be displayed by a JPopupMenu. This JPopupMenu will be filled dynamicly by a HashMap<String, JMenuItem> which represents each option in this JPopupMenu and it´s representing key. To accomplish this i wrote an abstract class which contains everything that needs to be done to create a custom right click menu, with two abstract methods. These methods will be overriden by subclasses of this class and will create two representing lists of Keys for the Map and theyr representing JMenuItem.
This is how the abstract class is designed.
public abstract class AbstractRightClickButton extends VButton{
    // The PopupMenu for this item;
    private JPopupMenu popup = new JPopupMenu();
    // The HashMap that stores the Menuitems and it´s keys
    private HashMap<String, JMenuItem> menuItems = new HashMap<String, JMenuItem>();
    // Stores the current selected key.
    private String choice= "";

    public AbstractRightClickButton() {
        this.menuItems = generateHashmap();
        initMouseListener();
        initPopUp();
    }

    // Abstract method to create an ArrayList of all JMenuItem
    public abstract ArrayList<JMenuItem> generateJMenuItemSide();
    // Abstract method to create an ArrayList for each key in the HashMap
    public abstract ArrayList<String> generateStringSide();

    private void initPopUp() {
        ArrayList<String> list = generateStringSide();
        for (String counter : list) {
            popup.add(menuItems.get(counter));
        }
    }

    private void initMouseListener() {
        this.addMouseListener(new MouseListener() {
            public void mousePressed(MouseEvent e) {
                if(SwingUtilities.isRightMouseButton(e)) {
                    // If the width of the popup is 0 then it wasn´t displayed yet. Just show it once and make it invisible again to get the width and height of the popup.
                    if (popup.getWidth() == 0)  {
                        popup.show(AbstractRightClickButton.this, AbstractRightClickButton.this.getWidth(), 0);
                        popup.setVisible(false);
                    }
                    popup.show(AbstractRightClickButton.this, AbstractRightClickButton.this.getWidth()-popup.getWidth(), 0);
                }
            }
            public void mouseExited(MouseEvent e) {}
            public void mouseEntered(MouseEvent e) {}
            public void mouseClicked(MouseEvent e) {}
            public void mouseReleased(MouseEvent e) {}
        });

    protected HashMap<String, JMenuItem> generateHashmap() {
        HashMap<String, JMenuItem> map = new HashMap<String, JMenuItem>();
        ArrayList<String> key = generateStringSide();
        ArrayList<JMenuItem> value = generateJMenuItemSide();
        for (int i = 0;i < key.size();++i) {
            map.put(key.get(i), value.get(i));
        }
        return map;
    };

    // This method is a helper method that can be called by subclasses of AbstractRightClickButton
    // It creates a JMenutButton based on the parameter
    protected JMenuItem generateJMenuItem(final String key, final boolean click) {
        JMenuItem item = new JMenuItem(new AbstractAction(key) {
            @Override
            public void actionPerformed(ActionEvent e) {
                choice = key;
                if (click) {
                    ActionEvent act  = new ActionEvent((Object)AbstractRightClickButton.this, ActionEvent.ACTION_PERFORMED, ""); // Button Event erstellen
                    AbstractRightClickButton.this.processEvent(act); // Event Processen um den Buttondruck Formsseitig auch auszulösen
                }
            }
        });
        return item;
    }
}

A concrete class would look like this
public class ConcreteRightClickButton extends AbstractRightClickButton{
    @Override
    public ArrayList<String> generateStringSide() {
        ArrayList<String> basis = new ArrayList<String>(0);

        basis.add("OPTION1");
        basis.add("OPTION2");

        return basis;
    }

    @Override
    public ArrayList<JMenuItem> generateJMenuItemSide() {
        ArrayList<JMenuItem> basis = new ArrayList<JMenuItem>(0);

        basis.add(generateJMenuItem("OPTION1", true));
        basis.add(generateJMenuItem("OPTION2", true));

        return basis;
    }
}

The problem i am facing depends on the type of button, espacially how this button is defined in the forms builder. If the button property iconic is defined as No, then the call of AbstractRightClickButton.this.processEvent(act) correctly processes this event and can be handelt by the When-Button-Pressed Event in Oracle Forms. But if the button property iconic is defined as Yes then the processing of the event somehow doesn´t work. While Debugging everything looks fine, there is no exception and it reaches the AbstractRightClickButton.this.processEvent(act) without any problem. But the representing When-Button-Pressed Trigger in Oracle Forms doesn´t react. Am i processing the Event incorrectly or is there something else that stops oracle forms from recieving this event?
I am using Oracle forms 11g to create a mask containing this specific button.

A: 1 year 8 months later, maybe this isn't an "answer" but its an alternative way to do the same thing.
Create a class that extends VBean, and create a JButton.
Add the jar to the classpath, and call it within a Bean Area.
It's called java pluggable components.
This page is useful:
JPC
EDIT:
import java.awt.Color;
import javax.swing.JButton;
import oracle.forms.ui.VBean;

public class TryButton extends VBean {

    JButton button = new JButton();

    public TryButton() {

        this.setSize(500, 500);
        this.setVisible(true);
        this.add(button);
        button.setSize(500, 500);
        button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imagen2.png")));
    }

}

Then, add the jar to: oracle_home/forms/java
and add it to classpath
In oracle forms in a new canvas create a Bean Area
Go to Item Properties and add the class package and name to: implementation class.


text:
Q: Como fazer strstr() em jquery Existe alguma forma de fazer strstr() (que existe no php) no jQuery?
Preciso criar uma function?
quero que seja verificado se existe a string exata que estou passando em outra string, por exemplo:
if(strstr("abc", "abcdefgh")){
...
}

A: Não é necessário jQuery para isso, apenas javascript puro, que já contém a função indexOf, exemplo.

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");

if (n > -1) alert('Termo encontrado');
else alert('Termo não encontrado');

Fonte

jQuery é uma biblioteca JavaScript cross-browser desenvolvida para simplificar os scripts client side que interagem com o HTML. Wikipédia

A: Use indexOf do javascript que retorna a posição de uma string em outra. Se o retorno de indexOf for -1 quer dizer que a primeira string não se encontra dentro da segunda.
Exemplo
if("string que contém".indexOf("string contida") < -1){
  /* O que fazer se não encontrar a string */
}
else{
  /* O que fazer se a string for encontrada. */
}

A: Sim, você vai precisar criar uma função.
<script type="text/javascript">

     var chave = /vai/;
     var string = "Como vai Amancio";
     var resultado = string.search(chave);

     if(resultado != -1){
        alert("Encontrado: " + resultado);
     }
     else{
        alert("Não foi possível encontrar");
     }
</script>

abraço!

A: Existe um projeto muito legal chamado php.js, nele existem implementações em Javascript das principais funções do PHP, incluindo a strstr(), sendo possível informar até mesmo o terceiro parâmetro.
Exemplo de uso:
strstr('Kevin van Zonneveld', 'van'); // Retorna 'van Zonneveld'


text:
Q: AppDomain.CurrentDomain.UnhandledException don't catch exception In my application I don't want that the application always crash if there was thrown a unhandled exception. I did some research and found a few EventHandlers.
On this Page is writtin:

In a typical WPF application you should use Application.Current.DispatcherUnhandledException for exceptions generated on the UI thread and AppDomain.CurrentDomain.UnhandledException for all the other exceptions.

In my case I need the Application.Current.DispatcherUnhandledException handler (I think so).
I did following. First in the App.xaml.cs OnStartup(...)-Method I wrote:
protected override void OnStartup(StartupEventArgs e)
{
    Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(Application_DispatcherUnhandledException);
}

I few rows below I created the method:
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    e.Handled = true;
    //TODO: StackTrace
    MessageBox.Show("An unhandled exception just occurred: " + e.Exception.Message + e.Exception.Data, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

Is that all I need?
In my MainView code-behind file I create a exception:
private void Button_Click(object sender, RoutedEventArgs e)()
{
    string asd = null;
    asd.Trim();
}

After executing my programm still crash with a System.NullReferenceException, because the string asd is null. What did I wrong.

A: AppDomain.CurrentDomain.UnhandledException is an event and cannot avoid app crash...
The only way to avoid application crash is to wrap your Application.Run method in a Try-Catch block. You will find it usually in Main() function.
The problem is that this can give you only the chance to restart the UI, because in the catch block your are outside the main loop...
I think the solution is writing better code, catching exceptions when necessary (if possible)...

A: Following is an extract from msdn.microsoft.com:

The UnhandledException event occurs when code executing by way of the Dispatcher throws an exception which is not handled.
  The UnhandledExceptionFilter event provides a means to not raise the UnhandledException event. The UnhandledExceptionFilter event is raised first, and If RequestCatch on the DispatcherUnhandledExceptionFilterEventArgs is set to false, the UnhandledException event will not be raised.

So I suggest to set Handled property of DispatcherUnhandledExceptionEventArgs class to true, i.e. e.Handled = true, in Application_DispatcherUnhandledException() method.
Update:
You can also use UnhandledExceptionFilter. Following is an extract from this link:

Remarks
This event is raised during the filter stage for an exception that is raised during execution of a delegate by way of Invoke or BeginInvoke and is uncaught.
The call stack is not unwound at this point (first-chance exception).
  Event handlers for this event must be written with care to avoid creating secondary exceptions and to catch any that occur. It is recommended to avoid allocating memory or doing any resource intensive operations in the handler.
The UnhandledExceptionFilter event provides a means to not raise the UnhandledException event. The UnhandledExceptionFilter event is raised first, and If RequestCatch on the DispatcherUnhandledExceptionFilterEventArgs is set to false, the UnhandledException event will not be raised.


text:
Q: request to https://registry.npmjs.org/solc failed, reason: certificate has expired request to https://registry.npmjs.org/solc failed, reason: certificate has expired
Installed node js and trying npm install -g solc for first time. I am not able to download anything . tried all options. I am behind company network vpn and i can access https://registry.npmjs.org/solc in all browsers. Trying for last 3 days.
Can anyone please advise.