text:
Q: Error my first Phonegap App with Mobile Angular Ui I have a problem...I want to create my first Phonegap App with Mobile Angular Ui...I'm seeing the official doc on the Mobile Angular UI...So I run this command:
> C:\Users\blabla>npm install -g bower yo gulp
> generator-mobileangularui

I receive this error...
> npm WARN engine yo@1.4.6: wanted: {"node":">=0.10.0","npm":">=2.1.0"}
> (current: {"node":"v0.10.29","npm":"1.4.14"}) |
>
>
> > buffertools@2.1.2 install C:\Users\blabla\AppData\Roaming\npm\node_m odules\generator-mobileangularui\node_modules\slug\node_modules\unicode\node_mod
> ules\bufferstream\node_modules\buffertools
> > node-gyp rebuild
>
> /
> C:\Users\blabla\AppData\Roaming\npm\node_modules\generator-mobileangul
> arui\node_modules\slug\node_modules\unicode\node_modules\bufferstream\node_modul
> es\buffertools>node "C:\Program
> Files\nodejs\node_modules\npm\bin\node-gyp-bin\\
> ..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild gyp ERR!
> configure error gyp ERR! stack Error: Can't find Python executable
> "python", you can set the PYT HON env variable. gyp ERR! stack     at
> failNoPython (C:\Program Files\nodejs\node_modules\npm\nod
> e_modules\node-gyp\lib\configure.js:103:14) gyp ERR! stack     at
> C:\Program Files\nodejs\node_modules\npm\node_modules\node
> -gyp\lib\configure.js:64:11 gyp ERR! stack     at Object.oncomplete (fs.js:107:15) gyp ERR! System Windows_NT 6.1.7601 gyp ERR! command
> "node" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modu
> les\\node-gyp\\bin\\node-gyp.js" "rebuild" gyp ERR! cwd
> C:\Users\blabla\AppData\Roaming\npm\node_modules\generato
> r-mobileangularui\node_modules\slug\node_modules\unicode\node_modules\bufferstre
> am\node_modules\buffertools gyp ERR! node -v v0.10.29 gyp ERR!
> node-gyp -v v0.13.1 gyp ERR! not ok npm WARN optional dep failed,
> continuing buffertools@2.1.2
>
>
> > unicode@0.6.1 postinstall C:\Users\blabla\AppData\Roaming\npm\node_m odules\generator-mobileangularui\node_modules\slug\node_modules\unicode
> > node install.js
>
> try to read file /usr/share/unicode/UnicodeData.txt . Warning: using
> slow naiv Buffer.indexOf function! `npm install buffertools` to speed
> things up. /usr/share/unicode/UnicodeData.txt not found. try to read
> file /usr/share/unicode-data/UnicodeData.txt .
> /usr/share/unicode-data/UnicodeData.txt not found. try to read file
> UnicodeData.txt . UnicodeData.txt not found. try to download . GET
> unicode.org:80/Public/UNIDATA/UnicodeData.txt
> C:\Users\blabla\AppData\Roaming\npm\gulp -> C:\Users\blabla\
> AppData\Roaming\npm\node_modules\gulp\bin\gulp.js
> C:\Users\blabla\AppData\Roaming\npm\yo -> C:\Users\blabla\Ap
> pData\Roaming\npm\node_modules\yo\lib\cli.js Error while downloading
> UnicodeData.txt: Error: connect ECONNREFUSED Please download file
> manually, put it next to the install.js file and run `node install.js`
> again. /
>
>
> > yo@1.4.6 postinstall C:\Users\blabla\AppData\Roaming\npm\node_module s\yo
> > yodoctor
>
> | Yeoman Doctor Running sanity checks on your system
>
> V Global configuration file is valid V NODE_PATH matches the npm root
> V No .bowerrc file in home directory V No .yo-rc.json file in home
> directory
>
> Everything looks all right! npm ERR! unicode@0.6.1 postinstall: `node
> install.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the
> unicode@0.6.1 postinstall script. npm ERR! This is most likely a
> problem with the unicode package, npm ERR! not with npm itself. npm
> ERR! Tell the author that this fails on your system: npm ERR!     node
> install.js npm ERR! You can get their info via: npm ERR!     npm owner
> ls unicode npm ERR! There is likely additional logging output above.
>
> npm ERR! System Windows_NT 6.1.7601 npm ERR! command "C:\\Program
> Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
> ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "bower" "yo"
> "gulp" "gen erator-mobileangularui" npm ERR! cwd C:\Users\blabla npm
> ERR! node -v v0.10.29 npm ERR! npm -v 1.4.14 npm ERR! code ELIFECYCLE
> C:\Users\blabla\AppData\Roaming\npm\bower -> C:\Users\blabla
> \AppData\Roaming\npm\node_modules\bower\bin\bower npm ERR! npm ERR!
> Additional logging details can be found in: npm ERR!
> C:\Users\blabla\npm-debug.log npm ERR! not ok code 0

Can I fix this problem??? Thanks!

A:
npm WARN engine yo@1.4.6: wanted: {"node":">=0.10.0","npm":">=2.1.0"} (current:n{"node":"v0.10.29","npm":"1.4.14"})

That means you need to update your npm. You can update the NPM using the following command:
npm install npm -g

You can update Node as well, but it's not mandatory. To update Node to the latest version, which is v0.12.2:
npm install node -g


text:
Q: App android crashing I do not understand why when I run the debug the application crashes. can anyone tell me where am I wrong?
  package com.example.locali;

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.util.Vector;

 import liuk.presences.R;

 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.StatusLine;
 import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.methods.HttpGet;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.json.JSONArray;
 import org.json.JSONObject;

 import android.os.Bundle;
 import android.app.Activity;

 import android.view.Menu;
 import android.widget.ArrayAdapter;
 import android.widget.ListAdapter;
 import android.widget.ListView;
 import android.widget.Toast;

 public class MainActivity extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      ListView listView = (ListView) findViewById(R.id.mylist);
      Vector v = new Vector();

      String readTwitterFeed = readTwitterFeed();
      try {
         JSONArray jsonArray = new JSONArray(readTwitterFeed);

         for (int i = 0; i < jsonArray.length(); i++)
         {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            v.add(jsonArray.getJSONObject(i).getString("Nome") +" "+ jsonArray.getJSONObject(i).getString("Cognome"));
         }
      } catch (Exception e) {
         Toast.makeText(this, "Exception" + e,Toast.LENGTH_LONG).show();
         e.printStackTrace();
      }
      ListAdapter listaContatti = new ArrayAdapter(this, android.R.layout.simple_list_item_1, v);
      listView.setAdapter(listaContatti);

      //Toast.makeText(this, "END OF APPLICATION",Toast.LENGTH_LONG).show();
   } //end onCreate

   public String readTwitterFeed() {
      StringBuilder builder = new StringBuilder();
      HttpClient client = new DefaultHttpClient();
      HttpGet httpGet = new HttpGet("http://locali.altervista.org/php/locali.php");

      try {
         HttpResponse response = client.execute(httpGet);
         StatusLine statusLine = response.getStatusLine();
         int statusCode = statusLine.getStatusCode();
         if (statusCode == 200) {

            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null)
            {
               builder.append(line);
            } //end while
         } else {
            Toast.makeText(this, "Failed to download file",Toast.LENGTH_LONG).show();
         }
      } catch (ClientProtocolException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
      return builder.toString();
   }
}

I read an online database with this application and I found this example on the internet. Thanks.
 03-07 18:21:10.490: D/AndroidRuntime(10119): Shutting down VM
 03-07 18:21:10.490: W/dalvikvm(10119): threadid=1: thread exiting with uncaught   exception (group=0x41da6da0)
 03-07 18:21:10.500: E/AndroidRuntime(10119): FATAL EXCEPTION: main
 03-07 18:21:10.500: E/AndroidRuntime(10119): Process: liuk.presences, PID: 10119
 03-07 18:21:10.500: E/AndroidRuntime(10119): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{liuk.presences/liuk.presences.LiukPresencesActivity}: java.lang.ClassNotFoundException: Didn't find class "liuk.presences.LiukPresencesActivity" on path: DexPathList[[zip file "/data/app/liuk.presences-2.apk"],nativeLibraryDirectories= [/data/app-lib/liuk.presences-2, /vendor/lib, /system/lib]]
03-07 18:21:10.500: E/AndroidRuntime(10119):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at android.app.ActivityThread.access$900(ActivityThread.java:161)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at android.os.Handler.dispatchMessage(Handler.java:102)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at android.os.Looper.loop(Looper.java:157)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at android.app.ActivityThread.main(ActivityThread.java:5356)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at java.lang.reflect.Method.invokeNative(Native Method)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at java.lang.reflect.Method.invoke(Method.java:515)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at dalvik.system.NativeStart.main(Native Method)
03-07 18:21:10.500: E/AndroidRuntime(10119): Caused by: java.lang.ClassNotFoundException: Didn't find class "liuk.presences.LiukPresencesActivity" on path: DexPathList[[zip file "/data/app/liuk.presences-2.apk"],nativeLibraryDirectories=[/data/app-lib/liuk.presences-2, /vendor/lib, /system/lib]]
03-07 18:21:10.500: E/AndroidRuntime(10119):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
03-07 18:21:10.500: E/AndroidRuntime(10119):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2222)
03-07 18:21:10.500: E/AndroidRuntime(10119):    ... 11 more
03-07 18:21:12.772: I/Process(10119): Sending signal. PID: 10119 SIG: 9

A: java.lang.ClassNotFoundException: Didn't find class "liuk.presences.LiukPresencesActivity"

You have declared liuk.presences.LiukPresencesActivity in your manifest. The code you posted has com.example.locali.MainActivity. Make sure the fully qualified class names (with package names) agree in manifest and code.

A: It seems you forgot to declare your activity in AndroidManifest.xml file
You should have such (or something like this with your activity name) text in your manifest xml file in application tag
<activity android:name="liuk.presences.LiukPresencesActivity" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: blacklist command not found in ubuntu 16.04 I am trying to use the command blacklist on my laptop which is Dell precision. I have Ubuntu 16.04 on it.
It shows the error below:
No command 'blacklist' found, did you mean:
command 'zblacklist' from package 'zmap' (universe)
blacklist command not found

Any advice what I must do....

A: To black list a module or driver you don't have to use a command "blacklist".
Open this file (Create it if it does not exist):
sudo nano /etc/modprobe.d/blacklist.conf

add a line like this:
blacklist nouveau

save the file, reboot the system. You can use modprobe -r nouveau to remove it temporary.


text:
Q: Delphi cannot find fileprovider.xml building Android I am trying to create a PDF document and then open it in an Android app. The code is based on the GitHub project https://github.com/AlessandroMartini/Delphi-Android-GeraPDF
I am using Delphi in RAD Studio 11.
I have successfully worked around the permissions to allow my app to save the file that it created and am now stuck at trying to view the file I have created using Intent to allow the file to be opened in another app to view it.
In my main form I have the following:
  Intent := TJIntent.Create;
  Intent.setAction(TJIntent.JavaClass.ACTION_VIEW);

  { based on solution from https://stackoverflow.com/questions/54535225/android-os-fileuriexposedexception-filename-exposed-beyond-app-through-intent }
  var lfile := TJFile.JavaClass.init(FileNameJ);
  Intent.setFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NO_HISTORY or
        TJIntent.JavaClass.FLAG_ACTIVITY_CLEAR_TOP);
  var LAuthority := TAndroidHelper.Context.getApplicationContext.getPackageName.concat(
        StringToJString('.fileprovider'));
  var Data := TJContent_FileProvider.JavaClass.getUriForFile(TAndroidHelper.Context,
        LAuthority,
        lFile);

  Intent.setDataAndType(Data, StringToJString('application/pdf'));

  TAndroidHelper.Activity.StartActivity(Intent);

This seems to be good so far.
My AndroidManifest.template.xml file is this, with the <provider></provider> section added to the default code:
<?xml version="1.0" encoding="utf-8"?>
<!-- BEGIN_INCLUDE(manifest) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="%package%"
    android:versionCode="%versionCode%"
    android:versionName="%versionName%"
    android:installLocation="%installLocation%">
    <uses-sdk android:minSdkVersion="%minSdkVersion%" android:targetSdkVersion="%targetSdkVersion%" />
<%uses-permission%>
    <uses-feature android:glEsVersion="0x00020000" android:required="true"/>
    <queries>
<%queries-child-elements%>
    </queries>
    <application
        android:persistent="%persistent%"
        android:restoreAnyVersion="%restoreAnyVersion%"
        android:label="%label%"
        android:debuggable="%debuggable%"
        android:largeHeap="%largeHeap%"
        android:icon="%icon%"
        android:theme="%theme%"
        android:hardwareAccelerated="%hardwareAccelerated%"
        android:resizeableActivity="false"
        android:requestLegacyExternalStorage="true">
<%provider%>
        <provider android:name="android.support.v4.content.FileProvider"
            android:authorities="%package%.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/fileprovider" />
        </provider>
<%application-meta-data%>
<%uses-libraries%>
<%services%>
        <!-- Our activity is a subclass of the built-in NativeActivity framework class.
             This will take care of integrating with our NDK code. -->
        <activity
            android:name="com.embarcadero.firemonkey.FMXNativeActivity"
            android:label="%activityLabel%"
            android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
            android:launchMode="singleTask">
            <!-- Tell NativeActivity the name of our .so -->
            <meta-data android:name="android.app.lib_name" android:value="%libNameValue%" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<%activity%>
<%receivers%>
    </application>
</manifest>
<!-- END_INCLUDE(manifest) -->

My fileprovider.xml file contains the following:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="external_files" path="."/>
</paths>

I am aware that the path value is not what I should be using, that I can fix later.
The problem comes after I have built this and try run it.
AndroidManifest.template.xml is in the root folder of my project source.
I have tried placing fileprovider.xml in the project root, ./res, ./xml and ./res/xml folders but I am getting a PAClient error indicating that fileprovider.xml can not be found.
[PAClient Error] Error: E2312 Unable to execute '"C:\Users\Public\Documents\Embarcadero\Studio\22.0\CatalogRepository\AndroidSDK-2525-22.0.42600.6491\build-tools\30.0.3\Aapt.exe" package -f -M "C:\Projects\Rad\JavaTest1\Android\Debug\TestPermissions\AndroidManifest.xml" -F "C:\Projects\Rad\JavaTest1\Android\Debug\TestPermissions\bin\TestPermissions-unaligned.apk" -I "C:\Users\Public\Documents\Embarcadero\Studio\22.0\CatalogRepository\AndroidSDK-2525-22.0.42600.6491\platforms\android-30\android.jar" -S "C:\Projects\Rad\JavaTest1\Android\Debug\TestPermissions\res" -A "C:\Projects\Rad\JavaTest1\Android\Debug\TestPermissions\assets" "C:\Projects\Rad\JavaTest1\Android\Debug\TestPermissions\library" "C:\Projects\Rad\JavaTest1\Android\Debug\TestPermissions\classes"' (Error 1)
[PAClient Error] Error: E2312 C:\Projects\Rad\JavaTest1\Android\Debug\TestPermissions\AndroidManifest.xml:38: error: Error: No resource found that matches the given name (at 'resource' with value '@xml/fileprovider').
Any ideas why fileprovider.xml is not found?

A: Found a solution from Dave Nottage at https://en.delphipraxis.net/topic/1361-android-how-to-call-a-tjintent/
In Delphi 10.3 and newer, the provider section does not need to be manually added to AndroidManifest.template.xml.
Change the Project Options, (right-click on the Project, then select Options).
In Application->Entitlement List, check Secure File Sharing.
If a provider section was manually added to AndroidManifest.template.xml then remove it.
The fileprovider.xml file is perfectly happy to be in the project source root.
Finally, make sure that the path indicated in fileprovider.xml is where the file(s) you want to share are located. In my case I am saving to '/storage/emulated/0/Download' so that is the value to put in fileprovider.xml.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="external_files" path="/storage/emulated/0/Download"/>
</paths>

Still got one problem though. Although the file is being placed in the /storage/emulated/0/Download folder, and the various possible PDF readers on my test phone can find the file, they are not able to open it. I can navigate to the Download folder and open the file using the same viewers, so it looks like I still have some permission issues in my App.


text:
Q: How to persist external Idp generated user access_token with WSO2 IS I've below usecase to be implemented :
A User should be able to login through External IDP's authorization_code grant flow into Service provider configured in WSO2 Identity Server -> This requirement has been achieved by adding External IDP & Configuring it as Federated authenticator in Service Provider.
Post login, We also want to persist External IDP's user access_token. So that we can invoke the external user specific APIs. Tried below approaches:

*

*Tried to publish External APIs in WSO2 API Manager, But in order to access the external API/resource we need current user's access token. As we can either configure Client Credentials/Resource owner password grant types which will either authorize a application or a specific user. But our usecase doesn't limit to specific user.

WSO2 APIM Endpoint Security Configurations
Would like to know how can I achieve my requirement by leveraging WSO2 IS & WSO2 API Manager(Only If required).
Any possible solutions around this requirment highly appreciated. Thanks in advance.
Environment
WSO2 IS -> v5.10.0
WSO2 API Manager -> v3.2.0

A: This accesstoken obtained by WSO2 IS onbehalf of the user is persisted to AuthenticationContext in the OIDC outbound connector. https://github.com/wso2-extensions/identity-outbound-auth-oidc/blob/master/components/org.wso2.carbon.identity.application.authenticator.oidc/src/main/java/org/wso2/carbon/identity/application/authenticator/oidc/OpenIDConnectAuthenticator.java#L486. After federated authentication is successful, SESSION_CREATE event will be published by Identity Server. So you can write an event handler and listen to this SESSION_CREATE event. Then you can get accesstoken from the authentication context using your EventHandler.
Docs on Event Handlers
https://is.docs.wso2.com/en/5.12.0/develop/writing-a-custom-event-handler/
https://medium.com/@isurakarunaratne/wso2-identity-server-eventing-framework-32505bcc1600
Refer this implementation for writing a custom event handler to listen to the SESSION_CREATE event. https://github.com/wso2-extensions/identity-inbound-auth-oauth/blob/master/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/bindings/handlers/TokenBindingExpiryEventHandler.java#L65


text:
Q: How to cache only anonymous(non-login) with ruby grape / garner? I'm using grape for api, devise for authentication, and thinking garner about caching api response.
I want to cache api response only if user-request hasn't login info.( Non-login status ). Then, how to do it?

*

*logined request serves normal response without caching, don't expires cache data(don't affect with caching).

*non-logined request serves response with caching

A: https://github.com/artsy/garner/issues/87#issuecomment-71453390
You need to bind with a different key depending on the logged in state. A nice way to accomplish that is to add a different_for_logged_in helper


text:
Q: Simulating Repository logic by Autowiring a bean from an interface that extends another interface I want to simulate the JpaRepositry logic by Autowiring the bean from another interface that extends the interface that the bean is implementing

the first interface :
public interface Test {
 String getBlaBla();
 String getWhatever();
  }

the bean:
    @Component
    public class TestImplementation implements Test {
    @Override
    public String getBlaBla() {
        return "BLA BLA";
    }

    @Override
    public String getWhatever() {
        return "WHATEVER";
    }
}

the second interface :
public interface TestTwo extends Test {
}

but I had a problem Autowiring the bean from TestTwo interface :
    @Autowired
    private TestTwo test;

I had problem of Could not autowire. No beans of 'TestTwo' type found
I did try to add @NoRepositoryBean over the interface TestTwo  but I kept having the same thing

A:
I did try to add @NoRepositoryBean over the interface TestTwo but I
  kept having the same thing

TestTwo is not a Spring repository interface, so it is ignored by Spring concerning this point.
The @NoRepositoryBean javadoc states indeed  :

Annotation to exclude repository interfaces from being picked up and
  thus in consequence getting an instance being created.

I will never work with your own interfaces out of the box.
Interfaces that extend JpaRepository are handled by Spring when the container start to give to them an implementation.
JpaRepository is a special interface handled by Spring.
In your case Spring doesn't handle the TestTwo interface in the same way.
To achieve such a thing or at least close things you should interest to CGLIB or AOP with Spring.


text:
Q: Sitecore Multi-Site: Prevent page in one site from appearing on another I've inherited the maintenance of a multi-site instance of Sitecore (v6.5) that we're starting to see some cross-talk of pages.  The content is structured as follows:
/sitecore
  /content
    /Site1
       /Metadata
         /Nav
         /archived pages
           /archived page1
       /Home Page
         /Internal Page1
    ...
      /Site2
       /Metadata
         /Nav
         /archived pages
       /Home PAge
         /InternalPages
    ...

For this example, site definitions are patched in such that www.site1.com has a rootPath of /sitecore/content/ and a home item Site1/Home page, www.site2.com has a similar rootPath of /sitecore/content/ and a home item Site2/Home page.
The content owners will move pages out from under the "Home Page" node to a folder called "archived pages" when they don't want them on the site anymore.
What I'm curious is if there is a way to prevent the following URL:
http://www.site2.com/sitecore/content/Site1/Metadata/archived1pages/archived-page1
Rendering.SiteResolving is currently set to true, so neither site should be producing links like this, but I'd like a way to have this sort of URL return a 404 without having to resort to writing a custom pipeline component. Am I missing a simple configuration to prevent this?

A: Try this, make "archived pages" folder item "un-publishable" on all sites, do a publish site (smart publish), now all of archived pages are not on web database, because the parent folder is not publishable, and you should see a 404 page when hit this URL:
http://www.site2.com/sitecore/content/Site1/Metadata/archived1pages/archived-page1


text:
Q: Pin a function pointer I need to pass a managed callback to an unmanaged TCP receiver. Since its a thread that needs to exist for the lifetime of the application, I need to prevent it from getting garbage collected. I have read everywhere that pinning function pointers is not required and the GCHandle.Alloc will do the job of preventing garbage collection.
But is this a given? I have seen that the AppPool hosting this code crashes with an access violation. Why should I not suspect the fact that this error occurs because the function pointer was garbage collected?
This post supports this fact.
Update:
This seems to have reduced the crashes considerably. Is there a problem with this approach?
typedef void (__cdecl *ProcMessageFunc)(void* param, void* paramBuf, ULONG bufSize);
FuncDelegate^ fp = gcnew MessageFuncDelegate(this, &Handler);
pin_ptr<MessageFuncDelegate^> pinnedFunctionPointer = &fp;
ret = Receiver ((ProcMessageFunc)pinnedFunctionPointer);

A: I do exactly what you suggest to do - GCHandle.Alloc on the delegate but with no pinning - and have not had any problems in extensive use on many different platforms and on .NET versions 2.0 - 4. Something like:
 DelegateHandle = GCHandle.Alloc(xlDelegate);
 FunctionPointer = Marshal.GetFunctionPointerForDelegate(xlDelegate);

with FunctionPointer then passed to the native code, and DelegateHandle kept for later cleanup.
This seems to be the best reference: http://msdn.microsoft.com/en-us/library/367eeye0(v=vs.80).aspx.
Nothing in the post you point to contradicts this reference - you do need to protect the delegate from garbage collection, it's just that pinning is not required.


text:
Q: Simple probabilty question got me stumped So here is the problem:
Six containers contain twenty four balls equally divided among each container (4 in each container). The color of the balls in each container is same and unique to that container. If we select two balls at random (without replacement) then what is the probability that they are of the same color.
So my reasoning is thus:
Total number of balls = 6*4 = 24. Total number of ways to select 2 balls is 24*23(denominator)
Number of ways to pick 2 balls from one container: 4*3 (similar balls). We can do this six times as there are six different containers. So total number of ways to pick two balls of same color = 4*3*6
Probability of picking same color is 4*3*6/(24*23) = 3/23
Am I on the right track?
Clarifications:
Each of the six containers has exactly 4 balls each. Each container has balls of a different color, so total of 24 balls with 6 different colors. I mean, container A has four balls of green, container B has four balls of yellow etc. In terms of selection, the question from what I recollect was "2 balls are chosen at random"

A: This boils down to the subject picking one of 6 urns at random each time.  That seems the most logical to me, there does not seem to be any likely process by which he will independently pick any of the 23 remaining balls on choice 2 with equal probability.
Therefore I think the chances that he picks any colour on choice 1 is 1.
On choice 2 the chances that he picks the same urn, and therefore the same colour is 1/6, hence the probability of two balls the same colour is 1/6

A: You're on the right track. To specify the number of ways of selecting balls of the same color, you need to specify the number of ways of selecting a color, and the no. of ways of choosing two balls of that color.


text:
Q: A Krull-Schmidt theorem for partially ordered groups If $G$ is a po-group (ie. partially ordered group), we say that $G$ is po-indecomposable if it's not the direct product of two non trivial subgroups (such subgroups are necessary convex and normal).
If a po-group $G$ has the ACC (ascending chain condition) or the DCC (descending chain condition) on convex normal subgroups, then we may verify that $G$ is a direct product of a finite number of po-indecomposable subgroups.
Can we have the uniqueness of such a decomposition like in the Krull-Schmidt theorem for abstract groups with the ACC or the DCC on normal subgroups.
Are there any articles on the subject ?


text:
Q: Out-of-the-box MVC ModelBinder for KendoUI AutoComplete I have not been able to find a way to easily read the ajax posted values sent by the KendoUI AutoComplete widget.
The documentation is lacking any details on this task. In fact all I could find for a server side code example was the following :
namespace Kendo.Mvc.Examples.Controllers
{
    using System.Web.Mvc;

    public partial class AutoCompleteController : Controller
    {
        public ActionResult ServerFiltering()
        {
            return View();
        }
   }
}

I was expecting the incoming data to auto-bind to a Kendo.Mvc.UI.DataSourceRequest but this isn't happening ...
Please, if you have efficiently dealt with a KendoUI AutoComplete widget, share your experience, TIA!

A: @David Perlman, I am completely editing this answer since I now understand your question better. In the Kendo example on Server Filtering they are using OData which has out of the box server filtering, something I was not aware of myself. If you use an MVC Controller like I do, you will have to modify the example and use a parameterMap like I will use in my new code example. In my example I have a simple table of "Sites" I use Entity Framework and I have a view wired directly to the Sites table. I have a class called Lookups.cs and I return a dynamic model GetSitesStartsWith(string startsWith) Like so:
  public dynamic GetSitesStartsWith(string startsWith)
    {
        return _context.vAaiomsSites
            .Select(s => new
            {
                ID = s.ID,
                SiteName = s.SiteName
            }).OrderBy(s => s.SiteName).Where(s => s.SiteName.StartsWith(startsWith));
    }

So in my Requisitions controller I create a JsonResult like so:
  public JsonResult GetSitesStartsWith(string startsWith)
    {

        var lookups = new Lookups();
        var data = lookups.GetSitesStartsWith(startsWith);
        return Json(data, JsonRequestBehavior.AllowGet);
    }

Last thing to do is add the AutoComplete code to the View that is wired to this JsonResult rather than to OData like so:

Sites

            <input id="sites" style="width: 250px" />

I have this example working and it does the filtering on the server, verified with developer tools. Let me know if you need any more help.

A: There is an EXCELLENT post describing how to work with Keno Autocomplete within MVC here.
If you decide to implement the code which is described there be sure to follow it very carefully.
Any and every discrepancy will probably break Kendo.


text:
Q: Vision text detection is resulting in calling OnSuccessListener multiple times I am using the sample code of mobile vision to perform text detection on an image. Here is the code
private void detectInVisionImage(
            FirebaseVisionImage image,
            final FrameMetadata metadata,
            final GraphicOverlay graphicOverlay) {
        detectInImage(image)
                .addOnSuccessListener(
                        new OnSuccessListener<T>() {
                            @Override
                            public void onSuccess(T results) {
                                shouldThrottle.set(false);
                                VisionProcessorBase.this.onSuccess(results, metadata,
                                        graphicOverlay);
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                shouldThrottle.set(false);
                                VisionProcessorBase.this.onFailure(e);
                            }
                        });
        // Begin throttling until this frame of input has been processed, either in onSuccess or
        // onFailure.
        shouldThrottle.set(true);
    }

For some reason, the onSuccessListener is being called so many times ( as if it is continuous detection). Although I call the detectInVisionImage only once on an image.
Why is this happening? A bug?
Thank you


text:
Q: How do I restrict signup to a product in Firebase If I create a new product, use simple auth, there is a "create user" API. How do I restrict it so that only invited emails (either by the email or via a one-time key) can sign up? Doesn't seem to fit easily into the rules, but I am probably missing something.

A: First, I should point out that the core Firebase API uses JSON Web Tokens for auth, which you can generate yourself, so you have full control over the creation of user accounts and can restrict it however you like:
https://www.firebase.com/docs/security/custom-login.html
I'm guessing you're referring to our Simple Login service.
Simple Login is a service that provides some common login options. It has no way to restrict creation of new accounts. However, you can restrict what those accounts can do with Firebase. For example, you could set your security rules up so that only user accounts in some authorized list (in Firebase) are actually able to read or write data.


text:
Q: Getting a token from an external web API is returning system.threading.tasks I'm successfully getting a token back from my GetAccessToken() and GetAccessTokenAsync methods, but the token isn't retrieved until after the main method of GetCourses, which won't work because that's the method that collects the data I need to show on my cshtml page. I've tried pulling apart this controller and creating a Globals class that will house just the URIs, apiKey, and token, but then I read that's bad practice for MVC so I ditched that effort. It was getting called after the GetCourses method anyway, so it was dead end too.
I'm newer to MVC and come from a WebForms background where I was used to being able to throw this kind of code in my PageInit, but am struggling to figure out how to pull this off in MVC. Can someone help me figure out what I am doing wrong or if I need to go about this a different way?
    public ActionResult GetCourses()
    {
        TempData["EthosURI"] = "redacted";
        TempData["Token"] = GetAccessToken().ToString();

        IEnumerable<Course> courses = null;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri((string)TempData["EthosURI"]);
            client.DefaultRequestHeaders.Add("Authorization", "Bearer {" + (string)TempData["Token"] + "}");
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            //HTTP GET
            var responseTask = client.GetAsync("courses");
            responseTask.Wait();

            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<IList<Course>>();
                readTask.Wait();

                courses = readTask.Result;
            }
            else //web api sent error response
            {
                //log response status here..

                courses = Enumerable.Empty<Course>();
                ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
            }
        }
        return View(courses);
    }

    public static async Task<string> GetAccessToken()
    {
        var token = await GetAccessTokenAsync("redactedUrl", "redactedAPIKey");
        return token;
    }
    public static async Task<string> GetAccessTokenAsync(string ethosURI, string apiKey)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(ethosURI);
            client.DefaultRequestHeaders.Accept.Clear();

            HttpRequestMessage request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(ethosURI)
            };
            request.Headers.Clear();
            request.Headers.Add("Authorization", $"Bearer {apiKey}");
            request.Headers.Add("Accept", "application/json");
            request.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true };

            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();

            return await response.Content.ReadAsStringAsync();
        }
    }

A: That's not how async works in C#. You need either to make GetCourses() async AND await for GetAccessToken(), or use dirty hack GetAccessToken().GetAwaiter().GetResult() but it may become not safe in certain circumstances.

A: The (non-blocking) way in C# to wait for a task to complete is to use the await keyword. And for a method to use the await keyword, it has to be marked async. By using await, you not only wait for the task to complete, but also the current thread is not blocked. Wrapping an asynchronous operation in another method would not make it synchronous. In other words, the asynchronous nature propagates up the call hierarchy and the caller has to await. So, the GetAccessToken() still has to be awaited.  A controller action can be marked asynchronous as well, so you probably want:
public async Task<ActionResult> GetCourses()
{
    TempData["EthosURI"] = "redacted";
    TempData["Token"] =  (await GetAccessToken()).ToString(); // note the additional parentheses
   ....

Note the additional parantheses above before calling ToString(). However, since GetAccessToken() already returns a string, you don't need the redundant ToString() call:
TempData["Token"] =  await GetAccessToken();

Now, you can also change this:
var readTask = result.Content.ReadAsAsync<IList<Course>>();
readTask.Wait();
courses = readTask.Result;

to just:
courses = await result.Content.ReadAsAsync<IList<Course>>();

Microsoft has quite good documentation on asynchronous programming and I would recommend checking it out.


text:
Q: How can I remove or ignore unwanted .snapshot in mounted volume? I am running a kubernetes cluster with NFS NAStorage, and when I mount volumes they get a .snapshot directory created at the mountpoint. This causes problems for example when using Helm Charts, as these don't expect an unknown Read Only directory in certain paths (e.g. chown ... <dir> can fail, crashing the container).
When installing the Graylog Helm Chart, I noticed the initContainer for the graylog pod crashing due to chown: ... Read-only file system after running the following chown line:
chown -R 1100:1100 /usr/share/graylog/data/

where the following volume is mounted:
...
volumeMounts:
  - mountPath: /usr/share/graylog/data/journal
    name: journal
...

I tried working around this by modifying the command to fail "quietly" by making it run : upon failure:
chown -fR 1100:1100 /usr/share/graylog/data/ || :

This made the initContainer succeed, but now the main container crashes instead, this time due to the mere presence of the .snapshot dir.
...
kafka.common.KafkaException: Found directory /usr/share/graylog/data/journal/.snapshot, '.snapshot' is not in the form of topic-partition
If a directory does not contain Kafka topic data it should not exist in Kafka's log directory
...

I have tried modifying the mount point of the volume, too, moving it up one level, but this causes new issues:
...
volumeMounts:
  - mountPath: /usr/share/graylog/data
    name: data-journal
...

com.github.joschi.jadconfig.ValidationException: Parent path /usr/share/graylog/data/journal for Node ID file at /usr/share/graylog/data/journal/node-id is not a directory

I would have expected there to be some way of disabling the creation of the .snapshot directory, ideally a way to unmount/never mount it in the first place. That, or any way to have the container properly ignore the directory entirely, to make it not interfere with the processes in the container, since it seems the very presence of it can seriously disrupt. However, I have yet to find anything of the sort, and I can't seem to find anyone having had a similar issue (the introduction of Volume Snapshots in kubernetes has not made the searching easier, to say the least).
Edit 1
I tried (semi successfully, I get the Parent path ... is not a directoryerror above) to implement subPath: journal, thus circumventing the .snapshot directory (or so I believe), but this still means potentially editing every Chart that is used in my cluster. Hopefully an alternative on a higher level can be found.
volumeMounts:
  - mountPath: /usr/share/graylog/data/journal
    name: data-journal
    subPath: journal

Edit 2
I am running a bare-metal cluster, with MetalLB and Nginx as loadbalancer+ingress controller.
The storage solution is provided by a third party provider, and it is from their backup solution that the .snapshot directory is made.
My imagined workaround
Since this will mainly be a problem when using Helm Charts or other deployments where volume mounts will be more or less out of our control, I will look into applying a "kustomization" that adds a single line to each volumeMount, adding
...
subPath: mount

or something like that. By doing that, I should be separating the actual mount point in the volume and the directory that actually gets mounted in the container by one level, keepin the .snapshot directory hidden in the abstract volume object. I will post my findings and potential kustomization that may come of it, if anyone else runs into a similar problem.
If someone thinks of a more streamlined solution, it is still very welcome - I'm sure it is possible to improve upon this one.

A: We finally got this fixed by the storage service provider, after them figuring out which configuration needed to be applied. If anyone has run into the same problem and needs to know which configuration, please reach out and I will ask our service provider.
The workaround that worked before we got the configuration fixed was as follows:
(Including --namespace is optional)

*

*Install mongodb-replicaset and elasticsearch (v 6.8.1)

$ helm install --name mongodb-replicaset --namespace graylog stable/mongodb-replicaset

# We add the elastic repo since the 'stable' repo will be deprecated further on
$ helm repo add elastic https://helm.elastic.co
# We run elasticsearch version 6.8.1 since Graylog v3 currently is incompatible with later versions.
$ helm install elastic/elasticsearch --name elasticsearch --namespace graylog --set imageTag=6.8.1

# Wait for deployments to complete, then you can test to see all went well
$ helm test mongodb-replicaset
$ helm test elasticsearch

*

*Extraxt Graylog deployment template

$ helm fetch --untar stable/graylog
$ helm dependency update graylog
$ helm template graylog  -n graylog -f graylog-values.yaml > graylog-template.yaml

#graylog-values.yaml
tags:
  install-mongodb: false
  install-elasticsearch: false
graylog:
  mongodb:
    uri: "mongodb://mongodb-replicaset-0.mongodb-replicaset.graylog.svc.cluster.local:27017/graylog?replicaSet=rs0"
  elasticsearch:
    hosts: "http://elasticsearch-client.graylog.svc.cluster.local:9200"
# + any further values

*

*Add namespace: graylog to all objects in graylog-template.yaml

*Add subPath: mount to all volumeMounts where a persistent volume is used (in this case name: journal) in graylog-template.yaml
...
        volumeMounts:
        - mountPath: /usr/share/graylog/data/journal
          name: journal
+         subPath: mount
...
        volumeMounts:
        - mountPath: /usr/share/graylog/data/journal
          name: journal
+         subPath: mount
...
  volumeClaimTemplates:
  - metadata:
      creationTimestamp: null
      name: journal

This can be done quickly in vim by typing :g/name: <volume-name>/norm osubPath: mount. Please note the lack of a space between "o" and "subPath", and note that this will add the line to the volumeClaimTemplate as well, which needs to be removed. "mount" can also be called something else.

*

*Deploy

$ kubectl apply -f graylog-template.yaml


text:
Q: Get custom windows form button event I have created a customize windows form and I just don't know how should I get access to the button click event when the button is inside the custom form and the method is in the main windows application.
thank you very much!

A: In your form, create a custom event and make it fire whenever the button is pressed:
public event EventHandler TheButtonClicked;

// Constructor
public CustomWindow()
{
  theButton.Click += FireTheButtonClicked;
}

public void FireTheButtonClicked(object sender, EventArgs e)
{
  if(TheButtonClicked != null) TheButtonClicked(this, e);
}

Now you have an event on your custom window that you can subscribe to from your main window.


text:
Q: Coerce an XTS object to TS for stock daily returns i'm scratching my head a lot of hours for this problem.
I've a xts object with stock return, but i need to coerce this object to ts .
Below there is an example.
date_vec <- as.Date(c("2010-01-05", "2010-01-06","2010-01-07",
                  "2010-01-08", "2010-01-11", "2010-01-12",
                  "2010-01-13"))

ret_vec <- rnorm(7)

ret_xts <- xts(ret_vec, order.by = date_vec)

As you can see, date are "discontinous" and when i try to force this to ts something goes wrong.
Thank you everyone for helping and sorry for my bad english.


text:
Q: MySQL: Правильно обновить данные после вставки Есть таблица

При вставки записи (с приложения/клиента), я заполняю поле «date».
Вопрос:
Существует возможность атоматом (на стороне сервера) как-нибудь заполнить поле «year_month» (тип INT), после заполнения «date»? если в этом поле должно отображаться «месяц» и «год» (введенного в «date»), если триггером этого сделать не выходит.
Или всетаки это должен делать клиент.
Спасибо.


text:
Q: Bootstrap action dropdown is not working inside table-responsive Bootstrap dropdown is not working in responsive as well as in desktop because i'm using this inside table-responsive and there is overflow property.
anybody can solve it?
Thanks

.dropdown-toggle{ cursor:pointer;}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Firstname
Email
Lastname
Password
Phone
Created By
Registration Date
Action

John
Doe
john@example.com
Password
Phone
Created By
Registration Date

Details

Document

Care Plan

Health Ins Info

Workers Comp Info

Personal Injury Info

Work Related Injuries

Motor Vehicle Accident

Medical History

Past Appointment

Upcoming Appointment

Authorization

Child Patient

Billing Record

John
Doe
john@example.com
Password
Phone
Created By
Registration Date

Details

Document

Care Plan

Health Ins Info

Workers Comp Info

Personal Injury Info

Work Related Injuries

Motor Vehicle Accident

Medical History

Past Appointment

Upcoming Appointment

Authorization

Child Patient

Billing Record

John
Doe
john@example.com
Password
Phone
Created By
Registration Date

Details

Document

Care Plan

Health Ins Info

Workers Comp Info

Personal Injury Info

Work Related Injuries

Motor Vehicle Accident

Medical History

Past Appointment

Upcoming Appointment

Authorization

Child Patient

Billing Record

John
Doe
john@example.com
Password
Phone
Created By
Registration Date

Details

Document

Care Plan

Health Ins Info

Workers Comp Info

Personal Injury Info

Work Related Injuries

Motor Vehicle Accident

Medical History

Past Appointment

Upcoming Appointment

Authorization

Child Patient

Billing Record

John
Doe
john@example.com
Password
Phone
Created By
Registration Date

Details

Document

Care Plan

Health Ins Info

Workers Comp Info

Personal Injury Info

Work Related Injuries

Motor Vehicle Accident

Medical History

Past Appointment

Upcoming Appointment

Authorization

Child Patient

Billing Record

A: Here you go with a solution https://jsfiddle.net/n2omqzpu/1/

$('a[class="dropdown-toggle"]').click(function(){
 var pos = $(this).closest('td').position();
  var ele = $(this).siblings('ul.dropdown-menu');
  var width = $(document).width() - 200;

  if( width > pos.left) {
    $(ele).css({
      left: pos.left,
      top: (pos.top + 20)
  });
  } else {
     $(ele).css({
      left: (pos.left - 180),
      top: (pos.top + 20)
     });
  }
});
.dropdown-toggle{ cursor:pointer;}

.dropdown-menu{
  position:fixed;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Firstname
Email
Lastname
Password
Phone
Created By
Registration Date
Action

John
Doe
john@example.com
Password
Phone
Created By
Registration Date

Details

Document

Care Plan

Health Ins Info

Workers Comp Info

Personal Injury Info

Work Related Injuries

Motor Vehicle Accident

Medical History

Past Appointment

Upcoming Appointment

Authorization

Child Patient

Billing Record

John
Doe
john@example.com
Password
Phone
Created By
Registration Date

Details

Document

Care Plan

Health Ins Info

Workers Comp Info

Personal Injury Info

Work Related Injuries

Motor Vehicle Accident

Medical History

Past Appointment

Upcoming Appointment

Authorization

Child Patient

Billing Record

John
Doe
john@example.com
Password
Phone
Created By
Registration Date

Details

Document

Care Plan

Health Ins Info

Workers Comp Info

Personal Injury Info

Work Related Injuries

Motor Vehicle Accident

Medical History

Past Appointment

Upcoming Appointment

Authorization

Child Patient

Billing Record

John
Doe
john@example.com
Password
Phone
Created By
Registration Date

Details

Document

Care Plan

Health Ins Info

Workers Comp Info

Personal Injury Info

Work Related Injuries

Motor Vehicle Accident

Medical History

Past Appointment

Upcoming Appointment

Authorization

Child Patient

Billing Record

John
Doe
john@example.com
Password
Phone
Created By
Registration Date

Details

Document

Care Plan

Health Ins Info

Workers Comp Info

Personal Injury Info

Work Related Injuries

Motor Vehicle Accident

Medical History

Past Appointment

Upcoming Appointment

Authorization

Child Patient

Billing Record

Little bit of dynamic calculation is required for positioning the dropdown element. Make the dropdown as position fixed.

A: In My system it is working. Just change your css code like this.
.dropdown-menu {
position: absolute;
top: 100%;
left: -135px;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
font-size: 14px;
text-align: left;
list-style: none;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0,0,0,.15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
box-shadow: 0 6px 12px rgba(0,0,0,.175);

}
If you need, chenge left value increased or decreased (left: -135px)


text:
Q: Parse error: syntax error, unexpected '?>', expecting function (T_FUNCTION) or const (T_CONST) I keep getting the error

Parse error: syntax error, unexpected '?>', expecting function
  (T_FUNCTION) or const (T_CONST)

From what I read this usually points to a missing "}", but everything seems to match up no matter how many times I read over it. I also tried removing one of the "}" in case I had one too many, but it came back with the error `

Parse error: syntax error, unexpected end of file

`.
Here's my code:
<?php
class Post{
     private $user_obj;
     private $con;

     public function __construct($con, $user){
            $this->con = $con;
            $this->user_obj = new User($con, $user);
     }

     public function submitPost($body, $user_to) {
         $body = strip_tags($body); //removes any HTML tags
         $body = mysqli_real_escape_string($this->con, $body); //Allows the use of " ' " so it doesn't think it's a new string.
         $check_empty = preg_replace('/\s+/', '', $body); //Deletes all spaces

         if($check_empty != "") {

             //Current date and time
             $date_added = date("Y-m-d H:i:s");
             //Get username
             $added_by = $this->user_obj->getUsername();

             //if user is on their own profile, user_to is 'none'
             if($user_to == $added_by) {
                 $user_to = "none";
             }

             //insert post
            $query = mysqli_query($this->con, "INSERT INTO posts VALUES('',
            '$body', '$added_by', '$user_to', '$date_added', 'no', 'no',
            '0')");

             $returned_id = mysqli_insert_id($this->con);

             //Insert notification

             //Update post count for user
             $num_posts = $this->user_obj->getNumPosts();
             $num_posts++;
             $update_query = mysqli_query($this->con, "UPDATE users SET
             num_posts='$num_posts' WHERE username='$added_by'");
         }
     }
?>

A:
You failed to close the class Try this

    <?php
class Post{
     private $user_obj;
     private $con;

     public function __construct($con, $user){
            $this->con = $con;
            $this->user_obj = new User($con, $user);
}

     public function submitPost($body, $user_to) {
         $body = strip_tags($body); //removes any HTML tags
         $body = mysqli_real_escape_string($this->con, $body); //Allows the
         use of " ' " so it doesn't think it's a new string.
         $check_empty = preg_replace('/\s+/', '', $body); //Deletes all
         spaces

         if($check_empty != "") {

             //Current date and time
             $date_added = date("Y-m-d H:i:s");
             //Get username
             $added_by = $this->user_obj->getUsername();

             //if user is on their own profile, user_to is 'none'
             if($user_to == $added_by) {
                 $user_to = "none";
             }

             //insert post
            $query = mysqli_query($this->con, "INSERT INTO posts VALUES('',
            '$body', '$added_by', '$user_to', '$date_added', 'no', 'no',
            '0')");

             $returned_id = mysqli_insert_id($this->con);

             //Insert notification

             //Update post count for user
             $num_posts = $this->user_obj->getNumPosts();
             $num_posts++;
             $update_query = mysqli_query($this->con, "UPDATE users SET
             num_posts='$num_posts' WHERE username='$added_by'");
             }
    }
}
    ?>

A: Add a } at end before ?>
Because you haven't closed your Class Post

A: I count 9 { and } combined. If it where right they where even. You're missing a } at the end i think,  but its hard to check on my phone.

A:
Note: First of all you need to flow coding style and change your coding pattern.
  https://www.php-fig.org/psr/psr-1/ look this page.


text:
Q: How to rewrite a URL using htaccess? I have read a few articles on rewriting using .htaccess and I still cannot fully get the outcome I was hoping for.
I have a url called: sitename.co.nf/Profile.php?u=Admin
Admin is my username.
I want to know how to rewrite the url as sitename.co.nf/$username
$username is a variable I have set up in my PHP code.
I tried using this rewrite without luck RewriteRule ^([a-zA-Z0-9_\-]+)/?$ Profile.php?u=$1
Here is some other userful code you may want to see...
if (isset($_GET['u'])) {
    $username = mysqli_real_escape_string($connect, $_GET['u']);
    if (ctype_alnum($username)) {
    //check user exists
    $check = mysqli_query($connect, "SELECT username FROM users WHERE username='$username'");
    if (mysqli_num_rows($check)===1) {
    $get = mysqli_fetch_assoc($check);
    $username = $get['username'];

    }


text:
Q: Requesting Advice On Preventing Ransomware (also very odd text in my win.ini cfg) I had just recently prevented a ransomware attack and am still looking for malware as I am curious. I had looked in my win.ini file this morning and found some odd text that even Google Translate couldn't decipher.
I am also looking for advice on how to combat these issues further than using a antivirus or malware program.

A: It looks like you're running Windows 7. Windows only uses a win.ini file in a very limited context, for 16-bit support. However, those win.ini files don't contain the content that yours does, so this one was almost definitely introduced by a third-party.
I tried typing the contents of the file into Google Translate myself and got this:

Easy to clean up
  Powered by Discuz!

Wikipedia says that Discuz is Chinese internet forum software, in which case we can assume Google mistakenly identified the language as Japanese, or this Chinese company actually is writing its Read Me files in Japanese.
If you've used Discuz or one of their products before on your machine, that would be an explanation for how this file got there, but even if you had, it's very suspect for any company to leave behind a file that looks like a Windows configuration file, and this alone could point to malicious motives. The software that left behind this .ini file could be the same one that tried to execute ransomware on your machine, or it could not. Either way, the forensics of the situation doesn't really matter much at this point.
You say you don't care about your data on this computer. If that's true, then the best way to proceed is to nuke it from orbit - that is, wipe it and start with a fresh install. Good malware can extricate itself deep into your system, and can make it difficult to next to impossible to truly undo the effects of. For this reason, in situations like yours where keeping old data isn't necessary, a fresh install of the operating system is a much quicker, less tedious solution than the painstaking work of (effectively) purging a system of all threats and then undoing the damage that those threats have wreaked.
You say you want to "combat" these issues "further than" using an antivirus, which I'll understand to mean that you've already run one or several, including at boot.
Beyond that, to make sure you're never in this situation again, it's about prevention. You do this by:

*

*Having a real-time (i.e on-access) antivirus installed and always running

*Making regular backups

*Regularly updating your operating system and programs

*Educating yourself on just how strongly hackers rely on social engineering, and then how to protect yourself from it


text:
Q: inexplicable Netbeans serializable warning for nested base class When I define the following class
public class Outer extends Outer.Inner {
    public static class Inner { }
}

Netbeans 6.9.1 gives me the "has no definition of serialVersionUID" warning for both Outer and Inner. I'm wondering if there is a legit reason for this warning, or if it's a bug. What about extending an inner class makes the compiler think they are implementing Serializable?
Note: This is more out of curiosity than wanting this unnecessary design pattern.

A: I've wondered the same thing myself. In lieu of an answer, I turned off the warning.
Tools -> Options Menu
Hints Tab -> Standard Javac warnings
Uncheck the serialization checkbox.
Now you'll have to be careful when extending Serialized Objects, but it stops annoying you about things that aren't serialized.


text:
Q: How do you stop linguini from changing file names? When you use the linguini.File resource, it will automatically prepend the file names with the lot name and 'pilot' (when run in pilot mode).  Is there a way to overide (i.e. stop) this behavior?

A: To stop the file resource from prepending the filename with the lot name, invoke it using the keyword share=True:
from linguini import File

File('/path/to/my', 'file.txt', share=True)

To stop the file resource from prepending the filename with 'pilot' (when run in pilot mode), invoke it with ignore_pilot=True.
File('/path/to/my', 'file.txt', ignore_pilot=True)

To stop it from making any changes at all to the file name, use the keyword static=True:
File('/path/to/my', 'file.txt', static=True)

Note that these settings don't change the value of self.lot or self.pilot within the resource---it only affects their inclusion in the file name.


text:
Q: Binary Search Tree "not a procedure" issue for In-Order-Traversal in Racket/Scheme/Lisp (define (inOrderTraverse root)
  (cond
    [(not (list? root)) (display root)]
    [else (
      (inOrderTraverse (getLeftChild root))
      (display (getValue root))
      (inOrderTraverse (getRightChild root))
    )]
  )
)

This gives me:

I tried replacing cond with if, but that didn't work.
I looked up online for similar approaches and found:
(define (inorder ~node func)
    (unless (empty? ~node)
      (inorder (node-left ~node) func)
      (print (node-val ~node)) (print ", ")
      (inorder (node-right ~node) func)))

from a gist of github/arjunvasan. After editing their code to fit mine, it worked perfectly, with the only difference being that they used unless instead of cond.
Why does unless work better here? I checked the racket docs on this keyword but still haven't found it.


text:
Q: PHP cURL, file_get_contents blank page I'm trying to get a page content with cURL or file_get_content. On many websites it's working but i'm trying to do that on a friend's server and it's not.
I think there is a protection with header or things like that. I get the following error code : 401 forbidden. If i try to reach the same page with a normal browser it works.
Here is my code for the file_get_contents function :
$homepage = file_get_contents('http://192.168.1.3');

echo $homepage; // just a test to see if the page is loaded, it's not.

if (preg_match("/my regex/", $homepage)) {
   // ... some code
}

I also tryed with cURL :
$url = urlencode('http://192.168.1.3');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0');
$result = curl_exec($ch) or die("Not working");
curl_close($ch);

echo $result; // not working ..

Nothing works, maybe i should add more args to curl_setopt ...
Thanks.
PS : If i try with linux (wget) i get an error, but if i try with aria2c it's working.

A: try this update with useragent
<?php
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, 'http://192.168.1.3/');
curl_setopt($curlSession,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
$homepage = curl_exec($curlSession);
curl_close($curlSession);
echo $homepage ;
?>

if still getting blank page you have to install this add-on on firefox and see the "request-headers" and "response-headers"

A: HTTP Status 401 means that UNAUTHORIZED. You need send the server with username and passwd。
With file_get_contents, you add the second param . That's a context-steam, which you can set header info.
You'd better to use curl for file_get_contents intend to access local file, as it's a block function.  Add the option as following, it's a basic authorize.
curl_setopt($ch,CURLOPT_USERPWD,"my_username:my_password");


text:
Q: Drag & Drop between to List with Custom ListItem i have multiple Lists with Custom ListItems (All of them have the same) and i want to have them sortable and be able to Drag & Drop them to another list.
All of this workes fine, but when i select a Droped ListItem i get an Exception that the item is not child of this widget. Also when i call the indexOf Method on the list with the listItem i get -1.
So when i call getChildren on the list (before and after the insert) the Element is in the list and the view also render it correctly even the selection!
Here is the code of my List:
qx.Class.define("padawan.quicksearch.SearchList", {
extend : qx.ui.form.List,

construct : function() {
    this.base(arguments);
    this.context = arguments[0];

    this.setHeight(null);

    this.setEnableInlineFind(false);

    this.setDroppable(true);
    this.setDraggable(true);

    // create the controller
    var controller = new qx.data.controller.List(null, this);
    controller.setDelegate({
        createItem : function() {
            return new padawan.quicksearch.SucheComposite(this.context);
        },
        bindItem : function(controller, item, id) {
            controller.bindProperty("", "model", null, item, id);
        }
    });

    // Create drag indicator
    var indicator = new qx.ui.core.Widget();
    indicator.setDecorator(new qx.ui.decoration.Decorator().set({
        widthTop : 1,
        styleTop : "solid",
        colorTop : "black"
    }));
    indicator.setHeight(0);
    indicator.setOpacity(0.5);
    indicator.setZIndex(100);
    indicator.setLayoutProperties({
        left : -1000,
        top : -1000
    });
    indicator.setDroppable(true);
    qx.core.Init.getApplication().getRoot().add(indicator);

    // Just add a move action
    this.addListener("dragstart", function(e) {
        var item = this.getSucheComposite(e.getOriginalTarget());

        if (!item) {
            e.preventDefault();
            return;
        }

        e.addType("items");
        e.addAction("move");
    });

    this.addListener("droprequest", function(e) {
      e.addData("items", [e.getDragTarget()]);
    }, this);

    this.addListener("dragend", function(e) {
        // Move indicator away
        indicator.setDomPosition(-1000, -1000);
    });

    this.addListener("drag", function(e) {
        var orig = e.getOriginalTarget();

        // if (!qx.ui.core.Widget.contains(this, orig) && orig != indicator)
        // {
        // return;
        // }

        var origCoords = orig.getContentLocation();

        indicator.setWidth(orig.getBounds().width);
        indicator.setDomPosition(origCoords.left, origCoords.top);
    });

    this.addListener("drop", function(e) {
        var selection = e.getData("items")[0];
        this.__reorderList(selection, e.getOriginalTarget(), e.getTarget());
    }, this);
},

members : {
    getSucheComposite : function(child) {
        if (child.classname == "padawan.quicksearch.SucheComposite")
            return child;

        while (child) {
            child = child.getLayoutParent();

            if ("padawan.quicksearch.SucheComposite" == child.classname) {
                return child;
            }
        }

        return child;
    },

    __reorderList : function(selection, target, list) {
        selection = this.getSucheComposite(selection);
        if (target.classname !== "padawan.quicksearch.SucheComposite" || !selection) {
            return;
        }

        switch(this.context.type){
        case 'Zeile':
            selection.setIsFilter(false);
            selection.setIsRow(true);
            selection.setIsColumn(false);
            break;
        case 'Filter':
            selection.setIsFilter(true);
            selection.setIsRow(false);
            selection.setIsColumn(false);
            break;
        case 'Spalte':
            selection.setIsFilter(false);
            selection.setIsRow(false);
            selection.setIsColumn(true);
            break;
        }

        list.addBefore(selection, target);
    }
}
});

A: Stupid mistake by me, i forgot to update the context for the listItem.


text:
Q: Silverlight, SignalR and IIS Applications off of the Default Web Site I'm using SignalR in a Silverlight 5 application. When I host my app in an "application" off of the default website in IIS 7.5 (i.e. localhost/subsite) Fiddler shows I get a 404 for "/signalr/negotiate".
It doesn't seem to take the IIS application path into account.  It should be requesting "/subsite/signalr/negotiate". How do I get it to use the correct url prefix?
Update:
I had to use the following code because it seems to be difficult to get the real root URI in a silverlight app without doing some parsing.
string xapLocationUri = Application.Current.Host.Source.AbsoluteUri;

string rootUri = xapLocationUri.Substring(0, xapLocationUri.IndexOf("/ClientBin"));

hubConnection = new HubConnection(rootUri);

You can't really rely on the following if you're hosted in an application off of the root web site in IIS:
Application.Current.Host.Source.GetComponents(UriComponents.Scheme | UriComponents.HostAndPort, UriFormat.Unescaped)


text:
Q: How to search record from table and display in gridview in c#? I'm new to .net, I have been created text box,drop down list and searc button.
When i select "starts with" in the drop down and type some characters in the text box and click search button, It should display records(according to search text) from table in gridview.
For that I created drop down, and create stored procedure.And i added following code:
Here is aspx:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:HiddenField ID="hiddenfield" runat="server" />
<asp:HiddenField ID="curricular" runat="server" />
    <asp:TextBox ID="searchid" runat="server" Visible="false"></asp:TextBox>

    <asp:Label ID="condition" runat="server" Visible="false" >
    </asp:Label>
    <asp:Label ID="searchtext" runat="server" Visible="false"></asp:Label>

<asp:DropDownList ID="searchrecord" runat="server" Width="150px"></asp:DropDownList>
<asp:TextBox ID="textsearch" runat="server"></asp:TextBox>
<asp:Button ID="searchclick" runat="server" text = "search" OnClick="searchrecords_Click" OnClientClick="return searchrecords();" />

Searched Records

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" DataSourceID="SqlDataSource1"
        OnRowCommand="GridView1_RowCommand"
        EnablePersistedSelection="True" BackColor="White"
        OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Height="240px"
        Width="755px">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
                ReadOnly="True" SortExpression="ID" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" />
            <asp:BoundField DataField="Section" HeaderText="Section"
                SortExpression="Section" />
            <asp:BoundField DataField="Address" HeaderText="Address"
                SortExpression="Address" />
                <asp:BoundField DataField="Email" HeaderText="Email"
                SortExpression="Email" />
            <asp:BoundField DataField="Mobilenum" HeaderText="Mobile Number"
                SortExpression="Mobile Number" />
                <asp:ImageField DataImageUrlField="Image" HeaderText="Image" ControlStyle-Width="50" ControlStyle-Height = "50">
                <ControlStyle Height="50px" Width="50px"></ControlStyle>
                </asp:ImageField>
                <asp:BoundField DataField="Extracurricular" HeaderText="Extracurricular"
                SortExpression="Name" />
        </Columns>
        <HeaderStyle BackColor="#FF0066" BorderColor="#CCFFFF" ForeColor="White"
            Height="50px" Width="50px" />
        <SelectedRowStyle BackColor="#FF66FF" />
    </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="sp_searchedstudentrecords"
        SelectCommandType="StoredProcedure">

    </asp:SqlDataSource>


text:
Q: Quality Center Modify Status of Automatic Runner via OTA
A simple need in Quality Center.
Background:
In HP Quality Center -> Test Lab, you can create a testset having many testcases. You can run the testset or individual testcase by clicking on the Run (which starts Test Run Scheduler). Considering that a test script  (considering Python) exists for the testcase, when Run is clicked a Automatic Runner popup is seen where you have three columns:
TestName, Run on Host, Status

I am aware of the OTA API which can be really useful to write a testscript.

My question is how can I modify the Final Status seen on the Automatic Runner via the testscript (and OTA API).
 I have this requirement because when my following testscript is called, I wish to display a message - 'Testcase Finished' instead of 'Error: Failed to Post Run'. The 2nd message is displayed because my testscript purposely cancels the Run. Here is the script:
def Test_Main(Debug, CurrentTestSet, CurrentTSTest, CurrentRun):
    TDOutput.Print('Do something before cancel')
    CurrentRun.CancelRun()
    TDOutput.Print('Do something after cancel')

A: The answer to this question is that.... it cannot be done!! The reason being, QC has its own way of knowing if the testscript passed successfully, it will make the status Passed. Like in the case of...
def Test_Main(Debug, CurrentTestSet, CurrentTSTest, CurrentRun):
    """
    """

    TDOutput.Print("Bye")

The status is Passed.
If any Traceback was caught in the script, it will show the error message and change the status to Failed or Not Complete. I guess QC did not make this tweak-able.
Only thing what we can do is store the output shown on the prompt and attach it to the Run.


text:
Q: Can I trick the treasure rooms in Brogue? Levels in Brogue often have a treasure room protected by a key somewhere else on the same level. There are usually 4 or 5 bits of treasure on altars in the room protected by cages. When you pick up an item from one altar, the rest of the cages close and you cannot pick a different item until you drop the current item back onto the altar where you picked it up. Of course, some of these rooms have multiple items that would help me greatly!
Is there a way to trick the room into opening all the cages or getting multiple items? I've tried dropping a different item onto an empty altar but that didn't work.

A: It's not possible.
Looking at the source code, we can see that treasure rooms ("libraries" as they're called internally - you can only check out one item at a time) are implemented using ALTAR_CAGE_OPEN features with the MF_GENERATE_ITEM and ITEM_IS_KEY flags - so, at level generation, each altar generates an item on it that is configured to be a key. (This is in Globals.c, although you'll have to read Rogue.h and Architect.c as well, and possibly drink heavily, to fit it all together.)
So, from this, we know that at generation time, the item on each altar is assigned as its key. Can we fake the key? Unfortunately, no. The key check is implemented in keyMatchesLocation() in Items.c, and reveals that each key is defined by three properties: the keyZ coordinate, the keyX and keyY coordinates, and the machine number.
A key only works when its keyZ matches the current level. keyZ is set (in Architect.c) to the current depth when the key is created, so a key will never work when taken off its home level. Assuming the keyZ matches, a key will work if either of the other two properties match: the keyX and keyY match the current location, or the machine at the current location has an ID that matches the key's machine ID. (The machine ID is generated at map generation time and is unique across the entire game.)
While it is in principle possible for multiple "keys" to exist for the same altar - you just need two key items with the same keyZ and machine ID - there's nothing in game that would cause this to happen. Similarly, there's no way to wedge a cage open (it has the DFF_EVACUATE_CREATURES_FIRST flag, so anything in the way gets pushed off it as it closes). It is possible that some sort of area effect that pushes items could be used to knock multiple items off their altars simultaneously, but Brogue has no such effects.
So, no, short of editing your save file to create a fake key item, it can't be done.

A: There is one class of item you can "trick," though. Wands count as "returned" even if they're empty of charges. So you can use a wand of empowerment on an ally and then return it for a different item.


text:
Q: How to use array inside while loop so it can track every id fetching from database? I'm fetching multiple rows from a database. That's why  I use a while loop but I need every individual ID inside the while loop. How can I use an array inside the while loop?
The friendid just prints the last result from the loop.I don't want to print the result inside the loop.
  while ($row = mysqli_fetch_assoc($run_sql))
   {
     $name = $row['name'];
     $friendid = $row['id'];
   }
    echo $friendid;

A: Try this
$ids = array();
  while ($row = mysqli_fetch_assoc($run_sql))
   {
     $name = $row['name'];
     $ids[] = $row['id'];
   }
   print_r($ids);

A: Create an empty array before the while loop. In each iteration of the loop, append the fetched row to this array.
$resultArr = array();
while ($row = mysqli_fetch_assoc($run_sql)){
    $resultArr[] = array($row['id'], $row['name']);
}
// display $resultArr array
var_dump($resultArr);


text:
Q: Alamofire auto refresh token and retry previous API call in iOS Swift 4 now I'm working on an iOS application in Swift 4. Here I'm using Alamofire to integrate the API calls. I need to integrate the right way to auto-refresh the authentication token and retry the previous API calls. I'm storing the authentication token once I logged in successfully. So after login, in each API, I'm appending the token in the header part. And when if the token is expired I will get 401. That time I need to auto-refresh the authentication token and recall the same API again. How can I do that? I checked in the Stackoverflow, but I didn't get any solution.
Here's my API Call,
import Foundation
import Alamofire
import SwiftyJSON

class LoveltyAPI {

    let loveltyURL = Bundle.main.object(forInfoDictionaryKey: "APIUrlString") as! String  // Main URL
    let buildVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String  //infoDictionary?["CFBundleShortVersionString"] as AnyObject
    weak var delegate:LoveltyProtocol?

    func get_profile(app_user_id:String, token:String) {
        let urlString = "\(loveltyURL)\(get_profile_string)?app_user_id=\(app_user_id)"
        let headers = ["Content-Type":"application/json","X-Requested-With":"XMLHttpRequest", "Authentication":"Token \(token)"]
        Alamofire.request(urlString, method: .get, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
            switch response.result {
            case .success:
                let swiftyJsonVar = JSON(response.result.value!)
                switch response.response?.statusCode {
                case 200, 201:
                    self.delegate?.getUserProfile!(response: swiftyJsonVar["data"].dictionaryObject as AnyObject)
                case 401:
                    self.delegate?.tokenExpired(response: tokenExpired as AnyObject)
                case 404:
                    self.delegate?.serviceError!(response: swiftyJsonVar["message"] as AnyObject)
                case 422:
                    self.delegate?.serviceError!(response: swiftyJsonVar["error"] as AnyObject)
                case 503:
                    self.delegate?.appDisabled(response: swiftyJsonVar.dictionaryObject as AnyObject)
                default:
                    self.delegate?.serviceError!(response: self.serverError as AnyObject)
                }
            case .failure(let error):
                self.delegate?.serviceError!(response: self.serverError as AnyObject)
            }
        }
    }
}

Please help me. If you can explain with my code, it would be very nice.

A: You can easily Refresh token and retry your previous API call using
Alamofire RequestInterceptor

NetworkManager.swift
import Alamofire
    class NetworkManager {
        static let shared: NetworkManager = {
            return NetworkManager()
        }()
        typealias completionHandler = ((Result<Data, CustomError>) -> Void)
        var request: Alamofire.Request?
        let retryLimit = 3

        func request(_ url: String, method: HTTPMethod = .get, parameters: Parameters? = nil,
                     encoding: ParameterEncoding = URLEncoding.queryString, headers: HTTPHeaders? = nil,
                     interceptor: RequestInterceptor? = nil, completion: @escaping completionHandler) {
            AF.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers, interceptor: interceptor ?? self).validate().responseJSON { (response) in
                if let data = response.data {
                    completion(.success(data))
                } else {
                    completion(.failure())
                }
            }
        }

    }

RequestInterceptor.swift
  import Alamofire
extension NetworkManager: RequestInterceptor {

    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        var request = urlRequest
        guard let token = UserDefaultsManager.shared.getToken() else {
            completion(.success(urlRequest))
            return
        }
        let bearerToken = "Bearer \(token)"
        request.setValue(bearerToken, forHTTPHeaderField: "Authorization")
        print("\nadapted; token added to the header field is: \(bearerToken)\n")
        completion(.success(request))
    }

    func retry(_ request: Request, for session: Session, dueTo error: Error,
               completion: @escaping (RetryResult) -> Void) {
       guard let statusCode = request.response?.statusCode else {
        completion(.doNotRetry)
        return
    }

    guard request.retryCount < retryLimit else {
        completion(.doNotRetry)
        return
    }
    print("retry statusCode....\(statusCode)")
    switch statusCode {
    case 200...299:
        completion(.doNotRetry)
    case 401:
        refreshToken { isSuccess in isSuccess ? completion(.retry) : completion(.doNotRetry) }
        break
    default:
        completion(.retry)
    }
    }

    func refreshToken(completion: @escaping (_ isSuccess: Bool) -> Void) {
                let params = [
"refresh_token": Helpers.getStringValueForKey(Constants.REFRESH_TOKEN)
        ]
        AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { response in
            if let data = response.data, let token = (try? JSONSerialization.jsonObject(with: data, options: [])
                as? [String: Any])?["access_token"] as? String {
                UserDefaultsManager.shared.setToken(token: token)
                print("\nRefresh token completed successfully. New token is: \(token)\n")
                completion(true)
            } else {
                completion(false)
            }
        }
    }

}

Alamofire v5 has a property named RequestInterceptor.
RequestInterceptor has two method, one is Adapt which assign
access_token to any Network call header, second one is Retry method.
In Retry method we can check response status code and call
refresh_token block to get new token and retry previous API again.

A: @m1sh0's answer was extremely helpful to me. I'm just adding the missing detail the OP asked for in the comments: How do you make the Alamofire request so that it uses the Retrier and Adapter?
I basically used @m1sh0's example and called it like this:
        var request_url = Constants.API_URL + "/path/to/resource"

        let sessionManager = Alamofire.SessionManager.default
        sessionManager.adapter = MyRequestAdapter.shared

        sessionManager.request(request_url).validate().responseJSON { (response: DataResponse<Any>) in
            switch(response.result) {
            case .success(_):
                print(response.result.value!)
                completion(response.result.value!)
            case .failure(_):
                print(response.result.error!)
                completion(response.result.error!)
                break
            }
        }

Note that you need validate() in the request in order to get retried on failure. Without it, the response is just returned for completion. Also note there's a failure case in the response block for all non-401 errors, as they are presumed unrecoverable.

A: You need Alamofire RequestRetrier and RequestAdapter check here
This is some example that I have:
import UIKit
import Alamofire

class MyRequestAdapter: RequestAdapter, RequestRetrier {
    private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?) -> Void

    private let lock = NSLock()

    private var isRefreshing = false
    private var requestsToRetry: [RequestRetryCompletion] = []
    var accessToken:String? = nil
    var refreshToken:String? = nil
    static let shared = MyRequestAdapter()

    private init(){
        let sessionManager = Alamofire.SessionManager.default
        sessionManager.adapter = self
        sessionManager.retrier = self
    }

    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
        var urlRequest = urlRequest

        if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(BASE_URL), !urlString.hasSuffix("/renew") {
            if let token = accessToken {
                urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
            }
        }
        return urlRequest
    }

    // MARK: - RequestRetrier

    func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
        lock.lock() ; defer { lock.unlock() }

        if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {
            requestsToRetry.append(completion)

            if !isRefreshing {
                refreshTokens { [weak self] succeeded, accessToken in
                    guard let strongSelf = self else { return }

                    strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() }

                    if let accessToken = accessToken {
                        strongSelf.accessToken = accessToken
                    }

                    strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) }
                    strongSelf.requestsToRetry.removeAll()
                }
            }
        } else {
            completion(false, 0.0)
        }
    }

    // MARK: - Private - Refresh Tokens

    private func refreshTokens(completion: @escaping RefreshCompletion) {
        guard !isRefreshing else { return }

        isRefreshing = true

        let urlString = "\(BASE_URL)token/renew"

        Alamofire.request(urlString, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: ["Authorization":"Bearer \(refreshToken!)"]).responseJSON { [weak self] response in
            guard let strongSelf = self else { return }
            if
                let json = response.result.value as? [String: Any],
                let accessToken = json["accessToken"] as? String
            {
                completion(true, accessToken)
            } else {
                completion(false, nil)
            }
            strongSelf.isRefreshing = false
        }

    }
}

My example is a little bit complex, but yes in general we have two important methods first one is adapt(_ urlRequest: URLRequest) throws -> URLRequest  where we attaching the token, here I have custom logic where one of the services have should not attach this token as a header. The second method is func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)  where I check what is the error code(in my example 401). And then I refresh my tokens with
 private func refreshTokens(completion: @escaping RefreshCompletion)

In my case, I have refresh token and access token and when I call the service with refresh token I should not append my old access token in the header. I think this is not best practice but it was implemented from peopele that I don't know.


text:
Q: sup as a colimit How does $\text{sup}$ become a (co)limit in a subset of $\mathbb{R}$?
Does it actually become $\text{lim}$ or $\text{colim}$?
I.e. I wish, in the natural order $\leq$ in $\mathbb{R}$, that the thin
subcategory $X$ in $\mathbb{R}$ naturally satisfies $\sup X=\text{(co)lim} X$
to see that $\mathbb{R}$ is (co)complete in the categorical sense.

A: Any topological space $X$ can become a category, whose objects are the open sets in $X$, and the morphisms are $$\mathrm{Hom}(U,V) := \begin{cases} V\hookrightarrow U & \text{if } V\subseteq U, \\ \varnothing & \text{otherwise.} \end{cases}$$
I'm not sure if you should reverse the inclusions like that. Either way, if $X$ is a bounded subset of $\mathbf{R}$, try inducing the order topology on it, and then take the colimit of all of its open subsets. I think you should take $X$ to be closed as well, which isn't a problem since the supremum of $X$ equals that of $\overline{X}$.
Also, you might instead want to define a category whose objects are the closed subsets of $X$.


text:
Q: WinDBG: How to get the underlying FILE_OBJECT from a WDFFILEOBJECT handle? I'm having a WDFFILEOBJECT handle(0x0000057fedd9b8b8), and I want to know its underlying FILE_OBJECT address, so that I can use !object xxxx to query the FILE_OBJECT's .PointerCount and .HandleCount. What windbg command can I use?
!wdfkd.wdfhandle 0x0000057fedd9b8b8 f0 does not seems to provide that information.

Were it a WDFDEVICE handle, I know !wdfkd.wdfdevice can tell me the underlying DEVICE_OBJECT, but what about WDFFILEOBJECT?
====== SOLVED (many days later) =====
According to snoone's hint, I figured it out. Live information below:
This time, FileObject=0x0000057fede811b8 .

I have to use !wdfkd.handle 0x0000057fede811b8 f0 first, because the handle value 0x0000057fede811b8 is not a valid kernel address, !wdfkd.handle tells the real kernel address for the KMDF FxObject behind the handle.

A: Try using the dt command specified in the output (dt wdf01000!FxFileObject 0x)


text:
Q: $SL_2 (\Bbb R) × SL_2 (\Bbb R)/ ± (I_2 , I_2 ) → (SO_{2,2})^\circ$ I went through this problem in Lie groups:

i) Prove that $SL_2 (\Bbb R) × SL_2 (\Bbb R)$ is a linear Lie group.

I identified $SL_2 (\Bbb R) × SL_2 (\Bbb R)$ with $\{\begin{pmatrix}
A & 0 \\
0 & D
\end{pmatrix} \in GL_4(\Bbb R), (A,D)\in SL_2 (\Bbb R) × SL_2 (\Bbb R) \}$

ii) Prove that $(M, N ) · A = M AN^{−1}$ is a topological group action
  of $SL_2 (\Bbb R) × SL_2 (\Bbb R)$ on $M_2 (\Bbb R)$ ,that preserves the déterminant.

I applied definitions...

iii) prove that the déterminant on $M_2(\Bbb R)$ is a quadratic form of signature $(2,2)$.

Done.

iv) Deduce a un morphism of Lie groups:
  $φ : SL_2 (\Bbb R) × SL_2 (\Bbb R)/ ± (I_2 , I_2 ) → (SO_{2,2})^\circ$ where $SO_{2,2}^\circ$ is the connected component of the neutral element of $SO_{2,2}$.

This is where I stuck and I need some help. How to use the questions above to solve this one? I have little knowledge about quadratic forms
Thank you for your help


text:
Q: What's the math behind the setRotateM function in android.opengl.matrix? There is a setRotateM function in android.opengl.matrix package and it

Converts Euler angles to a rotation matrix.

The principal part of the implementation is :
rm[rmOffset + 0]  =   cy * cz;
rm[rmOffset + 1]  =  -cy * sz;
rm[rmOffset + 2]  =   sy;
rm[rmOffset + 3]  =  0.0f;

rm[rmOffset + 4]  =  cxsy * cz + cx * sz;
rm[rmOffset + 5]  = -cxsy * sz + cx * cz;
rm[rmOffset + 6]  =  -sx * cy;
rm[rmOffset + 7]  =  0.0f;

rm[rmOffset + 8]  = -sxsy * cz + sx * sz;
rm[rmOffset + 9]  =  sxsy * sz + sx * cz;
rm[rmOffset + 10] =  cx * cy;
rm[rmOffset + 11] =  0.0f;

rm[rmOffset + 12] =  0.0f;
rm[rmOffset + 13] =  0.0f;
rm[rmOffset + 14] =  0.0f;
rm[rmOffset + 15] =  1.0f;

where cx = cos(angleOnX), sz = sin(angleOnZ) etc.
This bunch of code will give a 4x4 matrix:
[  cy*cz, cx*sz + cx*cz*sy, sx*sz - cz*sx*sy, 0]
[ -cy*sz, cx*cz - cx*sy*sz, cz*sx + sx*sy*sz, 0]
[     sy,           -cy*sx,            cx*cy, 0]
[      0,                0,                0, 1]

While, given rotation matrices around x, y, z axis respectively
Rx = [ 1,  0,   0, 0]
     [ 0, cx, -sx, 0]
     [ 0, sx,  cx, 0]
     [ 0,  0,   0, 1]

Ry = [  cy, 0, sy, 0]
     [   0, 1,  0, 0]
     [ -sy, 0, cy, 0]
     [   0, 0,  0, 1]

Rz = [ cz, -sz, 0, 0]
     [ sz,  cz, 0, 0]
     [  0,   0, 1, 0]
     [  0,   0, 0, 1]

The most similar composition I could find is
(Rx * Ry * Rz)^T = Rz^T * Ry^T * Rx^T =
[  cy*cz, cx*sz + cz*sx*sy, sx*sz - cx*cz*sy, 0]
[ -cy*sz, cx*cz - sx*sy*sz, cz*sx + cx*sy*sz, 0]
[     sy,           -cy*sx,            cx*cy, 0]
[      0,                0,                0, 1]

Between android's implementation R and raw multiplication Rxyz^T,
there are slight differences in R(1,2) R(1,3) R(2,2) R(2,3) components, where cx and sx are switched.
Considering android.opengl.matrix is a widely-applied, time-tested package, I must have done something wrong.
I have two questions:
1. How this difference happens?
2. Why it is (Rx * Ry * Rz)^T? I suppose it was Rz * Ry * Rx

A: question 1:  there is only one result in a right handed system using row or column vectors for a particuar order of rotations. so one of the formulas is wrong. maybe you included some terms from the projection matrix.
question 2: it's in x,y,z order because the rotations are done in that order (or the reverse).
the android version's difference might be due to the gui being a left handed system.


text:
Q: Externally trigger dag which has schedule_interval=None I have a controller dag named dss_controller
dag = DAG(
dag_id='dss_controller',
default_args={
    "owner": "dss admin",
    "start_date": datetime.utcnow(),
},
schedule_interval=None,
)

and a target dag named dss_trigger_target_dag
dag = DAG(
dag_id='dss_trigger_target_dag',
default_args=args,
schedule_interval=None,
)

Tasks are defined in both controller and target dags as in the default available examples.
This system works as expected when dss_controller's schedule_interval is set to "@once".
Then I have set it to None and triggered externally. It'll trigger the controller dag and move it to the running state and then move it to success state.
But it won't trigger dss_trigger_dagrun task of the controller dag.
What's reason for this behavior?
Setting schedule_interval=None was the reason, if so how?
This my controller dag,
import pprint
import pprint
from datetime import datetime

from airflow import DAG
from airflow.operators.dagrun_operator import TriggerDagRunOperator

pp = pprint.PrettyPrinter(indent=4)

def conditionally_trigger(context, dag_run_obj):
   """This function decides whether or not to Trigger the remote DAG"""
   c_p = context['params']['condition_param']
   print("Controller DAG : conditionally_trigger = {}".format(c_p))
   if context['params']['condition_param']:
      dag_run_obj.payload = {'message': context['params']['message']}
      pp.pprint(dag_run_obj.payload)
      return dag_run_obj

   # Define the DAG
   dag = DAG(
      dag_id='dss_controller',
    default_args={
        "owner": "dss admin",
        "start_date": datetime.utcnow(),
    },
    schedule_interval=None,
)

# Define the single task in this controller example DAG
trigger = TriggerDagRunOperator(
    task_id='dss_trigger_dagrun',
    trigger_dag_id="dss_trigger_target_dag",
    python_callable=conditionally_trigger,
    params={'condition_param': True, 'message': 'Hello Hasitha'},
    dag=dag,
)

and this is my target dag,
import pprint
from datetime import datetime

from airflow.models import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator

pp = pprint.PrettyPrinter(indent=4)

args = {
    'start_date': datetime.utcnow(),
    'owner': 'dss admin',
}

dag = DAG(
    dag_id='dss_trigger_target_dag',
    default_args=args,
    schedule_interval=None,
)

def run_this_func(ds, **kwargs):
    print("Remotely received value of {} for key=message".
          format(kwargs['dag_run'].conf['message']))

run_this = PythonOperator(
    task_id='target_run_this',
    provide_context=True,
    python_callable=run_this_func,
    dag=dag,
)

A: You have added "start_date" as now() in the default arguments, that go to each of the tasks. It seems, that is the real culprit. Airflow recommends against it since it can prevent triggering tasks ever.
Try setting the start date to something in the past, such as airflow.utils.dates.days_ago(1).

Refer: https://airflow.apache.org/faq.html#what-s-the-deal-with-start-date


text:
Q: How to get the same predictive search data that shows under the google search bar I'm trying to find a way to get the same predictive search results that shows under the Google search bar as your typing. I'm not talking about custom search for a specific site either. I thought this wasn't possible until I came across a new tab page extension from the chrome store.
https://chrome.google.com/webstore/detail/start-a-better-new-tab/kgifkabikplflflabkllnpidlbjjpgbp?hl=en
Their search bar predictions matches Google's exactly. What source are they getting that data from? Are there any other predictive search services/APIs that anyone can recommend?

A: "What source are they getting that data from?"
By looking at the extension's source code, this URL:
https://google.com/complete/search?client=firefox&hl=en&q=foo
It's the same API that Google uses on its search page. But that API is protected by CORS policy, so it can't be accessed from any webpage. A browser extension can, because it's granted more rights. To use it, you would need a proxy server (either your own, or a free one, such as the one in the example below).

const searchInput = document.getElementById('search'),
  suggestionsList = document.getElementById('suggestions');

searchInput.addEventListener('input', autocomplete);
autocomplete();

function autocomplete() {
  const q = searchInput.value;
  const proxy = 'https://cors-everywhere.herokuapp.com/';

  fetch(`${proxy}https://google.com/complete/search?client=firefox&hl=en&q=${q}`, {
    headers: { origin: 'google.com' }
  })
  .then(res => res.json())
  .then(res => {
    suggestionsList.innerHTML = res[1].map(x => `<li>${x}</li>`).join('')
  });
}
<input id="search" value="foo" />

"Are there any other ... services/APIs?"
We can't answer that here, as it's off-topic. This type of questions tend to attract opinionated answers and spam.