Q: Combine two different device capture frame into one frame and write a video I'm beginner in opencv but well versed in C#/C++.
I have created a openCV console app to capture and write frames data to videos from multiple devices or RTSP streams which is working fine.
I require to merge the output of two separate devices frames into one frame and write to video have done this in the snippet below but the video file generated is corrupted.
The video capture and video writer are set to grab at 1920 x 1080 resolution.
  for (int i = 0; i < devices; i++) {
  Mat frame;
  Mat f1, f2;
  //Grab frame from camera capture
  if (videoCapturePool[i].grab()) {
    videoCapturePool[i].retrieve(f1);
    f2 = f1.clone();
    if (isPause) {
      circle(f1, Point(f1.size().width / 2, f1.size().height / 2), 10, (255, 255, 10), -1);
      circle(f2, Point(f2.size().width / 2, f2.size().height / 2), 10, (255, 255, 10), -1);
    }
    hconcat(f1, f2, frame);

    imshow("Output", frame);

    waitKey(10);

    frameData[i].camerFrames.push_back(frame);
  }
  f1.release();
  f2.release();

}

for (int i = 0; i < devices; i++) {
  int32_t frame_width(static_cast < int32_t > (videoCapturePool[i].get(CV_CAP_PROP_FRAME_WIDTH)));
  int32_t frame_height(static_cast < int32_t > (videoCapturePool[i].get(CV_CAP_PROP_FRAME_HEIGHT)));

  VideoWriter vidwriter = VideoWriter(videoFilePaths[i], CV_FOURCC('M', 'J', 'P', 'G'), 30, Size(frame_width, frame_height), true);

  videoWriterPool.push_back(vidwriter);
  writer << frameData[i].camerFrames.size() << endl;
  for (size_t j = 0; j < frameData[i].camerFrames.size(); j++) {
    //write the frame
    videoWriterPool[i].write(frameData[i].camerFrames[j]);
  }
  frameData[i].camerFrames.clear();
}

A: Your approach must be generally refactored. I don't say about code - just about architecture. It has a big problem with memory - let's calculate!

*

*The size of the one RGB frame 1920x1080: frame_size = 1920 * 1080 * 3 = 6 Mb

*How many frames do you want capture from 2 cameras? For example 1 minute of video with 30 fps: video_size = 2 camera * 6 Mb/frame * 60 seconds = 21 Gb! Do you have so memory per process?
I advice to make queues in different threads for capture frames and 2 threads for pick up frames from capture queues and write it to files.


Q: Looking for XSL templates using Google Charts API? I am searching for examples on usage of ArcGIS Desktop HTML popups in general, being more specific on xsl templates using google charts api on it.
Are there any references available?

A: Here is reference to xsl with GC (google charts) which might be helpful.
csharp blog
And another showing "cool tool" for GC.
cool tool
here is a Wiki just scan down to google charts.
Wiki
And ESRI webhelp shows using an xsl (scroll down).
esri webhelp


Q: supoprtedInterfaceOrientation caled every time a rotation occurs supportedInterfaceOrientation should be called only once when viewDidLoad, but in my case it is called every time the simulator rotates.
I need only two orientations potrait and portrait upside down.
when i rotate to upside down the supported interface orientation is called 4 times and my view becomes upside down. on rotation to landscape it is called only once(but it shouldn't ?).
Any solution ?
PS: I am not using any Navigation controller so setting rotation equal to top view controller wont matter. And in my pList only 2 orientations are supported
Also I have a main View Controller in which I add subviews and I have set the supported interface orientation in my view controller.
Weird thing is 3 view controllers that are before(presented before) the faulty one, they
rotate just fine.

A: You can check the interfaceOrientation in viewDidLoad. You can get the interfaceOrientation with self.userInterFaceOrientation.
Maybe it would be better to check the interfaceOrientation in viewWillAppear.
The difference is, that viewDidLoad will only called one and viewWillAppear every time you enter that view.

A: Its so Simple you just click on your Project -> Summary -> Supported Interface Orientations. You can click the Interface Orientations as your requirements.


Q: HTML div with img in it displaying strangely On the website I'm working on (this), I have a div with an img in it. This is the html

<overlay> </overlay

<overlay> </overlay>

<overlay> </overlay>

nothing too complicated. This is the CSS for the classes img1, img2, and img3.
.img1
{
position:absolute;
left:12%;
}
.img2
{
display:block;
margin:auto;
}
.img3
{
position:absolute;
right:12%;
}

also pretty simple. But, if you look at the website, the 3rd image (at least for me on Safari) is much lower than the other two. Why would this happen? I don't see anything in the CSS or HTML that would cause this.

A: I've tried to do the best I can with your code, the following will work for you:

Note that <overlay> is not a valid HTML element. also I've seen on the page you used something like <margin>. It's not a good practice to invent HTML elements.. You can get all the functionality you need using regular
s (although I don't think this will break your page.. maybe only in older browsers..).
What I basically did:

*

*Wrapped the three
s with a container with text-align:center. This will make the three divs inside it aligned to the center.

*Added display:inline-block; to make all the divs follow the text-align.

*Added margins to the divs to space them

Note that I strongly recommend to replace your <overlay> with something like

A: If you have some markup like this:

Then I think this CSS will have approximately the effect you're after:
.wrapper {
    display: table;
    width: 960px;
}

.wrapper > div {
    display: table-cell;
    width: 33%;
    text-align: center;
}

.wrapper > div:hover img {
    opacity: 0.5;
}

Demo.  I set width: 960px; so that it would force things to be wider than the JSFiddle window, but you could set width: 100%; for your page.

A: div tag naturally stack vertically.  So you will need to add an id to each div or you could just put all the img in one div.
The block css attribute is effecting the layout.  It is pushing the next img to the next line.


Q: LAN networking not working between Ubuntu Saucy and OSX Mavericks with iPhone Hotspot At home, I have two machines (Ubuntu Saucy & OSX Mavericks) connected to my iPhone hotspot.  My iPhone is my gateway and I can access the internet from both machines.
Both machines are also able to resolve the IP address of the other when I use ping hostname.local.  However PING always returns:
"Destination Host Unreachable" when I ping OSX.local from Ubuntu, and
"Request timeout for icmp_seq##" when I ping Ubuntu.local from the Mac

SETTINGS
Ubuntu:
I installed samba and it's dependencies using sudo apt-get install samba samba-tools system-config-samba cifs-utils. I have shared my user's Public folder without password.
I have UFW turned off. Ubuntu is connected to the iPhone via wireless (ip 172.20.10.3)
Mac:
I have enabled File Sharing for my user's Public folder with read access to everyone.
Other settings are default. OSX is connected to the iPhone through the USB (ip 172.20.10.2)
OTHER
On Ubuntu: in Nautilus' Browse Network window; I can see two icons for OSX(File Sharing), Ubuntu, and Windows Network.
On OSX:  I can't see anything in the Network folder (though I see home and net at the same level, and both are also empty)
When I double click the OSX(File Sharing) icon, I get a message 'Unable to access location'.
Any suggestions on what else I should do to enable file sharing between the two?
Cheers,
Nap

A: Buy a wifi router, host a web-site on ubuntu (e.g nginx), make an html which contains url for the files you want to download, then just type 192.168.1.2 yyghjj


Q: inflating class org.osmdroid.views.MapView cause crash I use eclipse as IDE to write a simple test program that put some TextView and Button on the screen and works fine.
Then, I do...
(1) set compiler compliance level to 15
(2) set ANDROID_SDK_PLATFORM to C:/ADT/sdk/platforms/android-15
(3)add these as external JARs
osmdroid-android-4.2.jar
slf4j-android-1.7.7.jar

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="15"
    android:targetSdkVersion="15" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.test.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category
android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

fragment_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.test.MainActivity$PlaceholderFragment" >

 <Button
    android:id="@+id/bt_test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="test" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/bt_test"
    android:text="@string/hello_world"
    android:textSize="24sp" />

<org.osmdroid.views.MapView
    android:id="@+id/mapview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</RelativeLayout>

MainActivity.java
package com.example.test;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

import org.osmdroid.views.MapView;

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        // return rootView;

        getActivity().setContentView(R.layout.fragment_main);
        return null;
    }
}

}

compilation ok, apk installation ok, but app crash...
(I use a real phone with android 4.2.2 as debug device.)
Here comes the log:
06-06 23:03:06.007: D/jdwp(18476): sendBufferedRequest : len=0x3B
06-06 23:03:06.013: D/dalvikvm(18476): open_cached_dex_file :
/data/app/com.example.test-1.apk /data/dalvik-
cache/data@app@com.example.test-1.apk@classes.dex
06-06 23:03:06.027: D/skia(18476): Flag is not 10
06-06 23:03:06.029: D/skia(18476): Flag is not 10
06-06 23:03:06.032: W/IconCustomizer(18476): can't load
transform_config.xml
06-06 23:03:06.035: D/skia(18476): Flag is not 10
06-06 23:03:06.040: D/skia(18476): Flag is not 10
06-06 23:03:06.043: D/skia(18476): Flag is not 10
06-06 23:03:06.058: D/skia(18476): Flag is not 10
06-06 23:03:06.060: D/skia(18476): Flag is not 10
06-06 23:03:06.066: D/skia(18476): Flag is not 10
06-06 23:03:06.067: D/skia(18476): Flag is not 10
06-06 23:03:06.069: D/skia(18476): Flag is not 10
06-06 23:03:06.071: D/skia(18476): Flag is not 10
06-06 23:03:06.072: D/skia(18476): Flag is not 10
06-06 23:03:06.077: V/Provider/Settings(18476): invalidate
[secure]: current 7 != cached 0
06-06 23:03:06.080: V/Provider/Settings(18476): from db cache, name
= access_control_lock_enabled , value = null
06-06 23:03:06.111: D/libEGL(18476): loaded
/vendor/lib/egl/libEGL_mtk.so
06-06 23:03:06.114: D/libEGL(18476): loaded
/vendor/lib/egl/libGLESv1_CM_mtk.so
06-06 23:03:06.117: D/libEGL(18476): loaded
/vendor/lib/egl/libGLESv2_mtk.so
06-06 23:03:06.252: D/OpenGLRenderer(18476): Enabling debug mode 0
06-06 23:03:06.253: V/InputMethodManager(18476): onWindowFocus:
null softInputMode=288 first=true flags=#9810100
06-06 23:03:06.254: V/InputMethodManager(18476): START INPUT:
com.android.internal.policy.impl.PhoneWindow$DecorView{4221c418
V.E..... R.....ID 0,0-720,1280} ic=null
tba=android.view.inputmethod.EditorInfo@42289610 controlFlags=#104
06-06 23:03:06.256: V/InputMethodManager(18476): Starting input:
Bind result=InputBindResult{null
com.cootek.smartinputv5/.TouchPalIME #4739}
06-06 23:03:06.265: D/skia(18476): Flag is not 10
06-06 23:03:08.041: I/SurfaceTextureClient(18476):
[STC::queueBuffer] (this:0x5c2c73f8) fps:0.57, dur:1745.04,
max:1745.04, min:1745.04
06-06 23:03:08.627: D/OpenGLRenderer(18476): Flushing caches (mode
0)
06-06 23:03:08.845: D/OpenGLRenderer(18476): Flushing caches (mode
1)
06-06 23:03:08.849: D/OpenGLRenderer(18476): Flushing caches (mode
0)
06-06 23:03:45.893: D/jdwp(18569): sendBufferedRequest : len=0x3B
06-06 23:03:45.899: D/dalvikvm(18569): open_cached_dex_file :
/data/app/com.example.test-2.apk /data/dalvik-
cache/data@app@com.example.test-2.apk@classes.dex
06-06 23:03:45.911: D/skia(18569): Flag is not 10
06-06 23:03:45.914: D/skia(18569): Flag is not 10
06-06 23:03:45.918: W/IconCustomizer(18569): can't load
transform_config.xml
06-06 23:03:45.921: D/skia(18569): Flag is not 10
06-06 23:03:45.925: D/skia(18569): Flag is not 10
06-06 23:03:45.929: D/skia(18569): Flag is not 10
06-06 23:03:45.942: D/skia(18569): Flag is not 10
06-06 23:03:45.944: D/skia(18569): Flag is not 10
06-06 23:03:45.950: D/skia(18569): Flag is not 10
06-06 23:03:45.952: D/skia(18569): Flag is not 10
06-06 23:03:45.953: D/skia(18569): Flag is not 10
06-06 23:03:45.955: D/skia(18569): Flag is not 10
06-06 23:03:45.956: D/skia(18569): Flag is not 10
06-06 23:03:45.961: D/AndroidRuntime(18569): Shutting down VM
06-06 23:03:45.961: W/dalvikvm(18569): threadid=1: thread exiting
with uncaught exception (group=0x419d59a8)
06-06 23:03:45.964: E/AndroidRuntime(18569): FATAL EXCEPTION: main
06-06 23:03:45.964: E/AndroidRuntime(18569):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.test/com.example.test.MainActivity}:
android.view.InflateException: Binary XML file line #24: Error
inflating class org.osmdroid.views.MapView
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.ActivityThread.performLaunchActivity(
ActivityThread.java:2333)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.ActivityThread.handleLaunchActivity(
ActivityThread.java:2385)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.ActivityThread.access$600(ActivityThread.java:157)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.ActivityThread$H.handleMessage(
ActivityThread.java:1341)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.os.Handler.dispatchMessage(Handler.java:99)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.os.Looper.loop(Looper.java:153)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.ActivityThread.main(ActivityThread.java:5322)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
java.lang.reflect.Method.invokeNative(Native Method)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
java.lang.reflect.Method.invoke(Method.java:511)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:848)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
dalvik.system.NativeStart.main(Native Method)
06-06 23:03:45.964: E/AndroidRuntime(18569): Caused by:
android.view.InflateException: Binary XML file line #24: Error
inflating class org.osmdroid.views.MapView
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.view.LayoutInflater.createViewFromTag
(LayoutInflater.java:768)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.view.LayoutInflater.rInflate(LayoutInflater.java:816)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.view.LayoutInflater.inflate(LayoutInflater.java:559)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.view.LayoutInflater.inflate(LayoutInflater.java:466)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.view.LayoutInflater.inflate(LayoutInflater.java:419)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
com.android.internal.policy.impl.PhoneWindow.setContentView
(PhoneWindow.java:354)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.Activity.setContentView(Activity.java:1981)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
com.example.test.MainActivity$PlaceholderFragment.onCreateView
(MainActivity.java:63)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.Fragment.performCreateView(Fragment.java:1695)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.FragmentManagerImpl.moveToState
(FragmentManager.java:885)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.FragmentManagerImpl.moveToState
(FragmentManager.java:1057)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.BackStackRecord.run(BackStackRecord.java:694)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.FragmentManagerImpl.execPendingActions
(FragmentManager.java:1435)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.Activity.performStart(Activity.java:5233)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:2306)
06-06 23:03:45.964: E/AndroidRuntime(18569):    ... 11 more
06-06 23:03:45.964: E/AndroidRuntime(18569): Caused by:
java.lang.ClassNotFoundException: Didn't find class
"org.osmdroid.views.MapView" on path: DexPathList[[zip file
"/data/app/com.example.test-2.apk"],nativeLibraryDirectories=
[/data/app-lib/com.example.test-2, /vendor/lib, /system/lib]]
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
dalvik.system.BaseDexClassLoader.findClass
(BaseDexClassLoader.java:53)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
java.lang.ClassLoader.loadClass(ClassLoader.java:501)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
java.lang.ClassLoader.loadClass(ClassLoader.java:461)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.view.LayoutInflater.createView(LayoutInflater.java:622)
06-06 23:03:45.964: E/AndroidRuntime(18569):    at
android.view.LayoutInflater.createViewFromTag
(LayoutInflater.java:757)
06-06 23:03:45.964: E/AndroidRuntime(18569):    ... 25 more
06-06 23:03:48.547: I/Process(18569): Sending signal.
PID: 18569 SIG: 9

A: I solve it. Add osmdroid-android-4.2.jar, osmdroid-third-party-4.2.jar, slf4j-android-1.7.7.jar and slf4j-api-1.7.7 as external JARs. And put all four files into the libs directory of the "test" project.


Q: segmentation fault using pointers on array of strings hi there i have this test code written that produces a segmentation fault on third iteration of while... using a debugger i saw the value of tokens[count] and it is correct but in the last iteration there is a segmentation fault,
str_split divide the string using ; as divisor(it works)
anybody can help?
   sportello[0].elenco_ris[0]=strdup("string;of;test");
   tokens=str_split(sportello[0].elenco_ris[0],';');

   int p=0;
   int count=0;
   int lungh=strlen("");
        while(p!=-1){
            lungh=strlen(tokens[count]);
            if(lungh!=0){
                printf("\nprinto: %s",tokens[count]);
                count++;
            }
            else p=-1;

        }

print: string
print: of
RUN FINISHED; Segmentation fault; real time: 0ms; user: 0ms; system: 0ms

A: ok i solved..the problem was what i thought...thaks to a comment by @Joachim Pileborg i've tried with this (NULL)... so thanks to you all
`int p=0;
       int count=0;
            while(p!=-1){
                if (tokens[count] != NULL){
                    printf("\nprinto: %s",tokens[count]);
                    count++;
                }
                else p=-1;

            }`

A: the segmentation fault occures when the process execute strlen(tokens[count]) inside the IF at the last iteration..the return value would be 0(no string?) but instead seg fault...
probably in that location there isn't a string so this occures...how can i solve the problem? anyway this is str_split,it is the same(more or less) posted on this site somewhere,it works
char** str_split(char* a_str, char a_delim) {
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;

/* Count how many elements will be extracted. */
while (*tmp) {
    if (a_delim == *tmp) {
        count++;
        last_comma = tmp;
    }
    tmp++;
}

/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);

/* Add space for terminating null string so caller
   knows where the list of returned strings ends. */
count++;

result = malloc(sizeof (char*) * count);

if (result) {
    size_t idx = 0;
    char* token = strtok(a_str, delim);

    while (token) {
        assert(idx < count);
        *(result + idx++) = strdup(token);
        token = strtok(0, delim);
    }
    assert(idx == count - 1);
    *(result + idx) = 0;
}

return result;

}


Q: Make VSCode apply syntax highlighting to .tsx files Trying to start a gatsby+react+typescript project and VSCode will only apply syntax highlighting to the HTML in my .tsx files. The typescript code remains a single color. How do I fix this?
Note: I have no plugins installed at the moment and the highlighting works if the file type is set to .jsx

A: Clicking on the language button in the lower right corner and selecting typescript react fixed the problem.

A: I faced same problem, even "Typescript React" was selected as the language. I had to click and select the language pack  version before getting syntax highlighting working.

A: In my case "JavaScript and TypeScript Nightly" extension was causing the problem.
I had the same problem even when "Typescript React" was selected.
I disabled all the extensions and problem solved.
Then I enabled each extension individually and I've found out "JavaScript and TypeScript Nightly" was causing the problem.
I hope this will help someone.

A: I solved this issue just reloading vscode as required by JavaScript and TypeScript Nightly extension, once it was reload I just double checked that Typescript react was selected and the problem was resolved.
Seems like the real problem was that the library JavaScript and TypeScript Nightly was not fully reloaded.


Q: Android kotlin calling same api with different date params and inserting to room all together I have an api to return data based on from and to date params. The api is limited to return only 1 day data at a time. I need to fetch data for 7 days and insert it to room db. Fetching day by day and inserting to db is time consuming and hence causing bad user experience.

*

*How can I make 7 parallel calls to same api with different date params?

*After making all 7 parallel api calls, how can I combine the responses and bulk insert to room
db

*Is there any other better way to fetch the entire data and insert to db with minimal time.

My code to fetch single day data is as follows.
               runBlocking {
                val queryParams = BaseQuery(
                    device_id = "12345",
                    date_from = fromDate,
                    date_to = toDate,
                    quantity = "200"
                )
                myDataUsecase.executeFetchDataUseCase(queryParams.asMap)
                    .onStart {
                        // DO Something when this starts
                    }
                    .catch { exception ->
                        // Catch any exception here and log it
                    }
                    .collect {
                            baseResult -> parseBaseResult(baseResult)
                    }
                 }

How can I achieve my requirement in an efficient way? Any suggestions are appreciated.


Q: How to check mulitple data in rows using javascript? I have check calculation in rows of data.
Here is my row format.

When I have select first row of "Purchase Document". It will automaticaly fill the value in its row fields. As per shown in image.
Now In second row, when I select "Purchase Document" with same value then, I need to calculate of LPO AMT (Total Amount), Pending Amout & Amount.
Means if there Amount fill with 1000 then in second row it will not be more then 23500 (Pending Amount).
Here my code :
function doLPOamt(val) {
        var req = Inint_AJAX();
        req.onreadystatechange = function () {
            if (req.readyState==4) {
                if (req.status==200) {
                    document.getElementById('LPO_AMT').value="";
                    document.getElementById('LPO_AMT').value=req.responseText; //retuen value
                }
            }
        };
        req.open("GET", "lpoamnt.php?val="+val); //make connection
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
        req.send(null); //send value
    }

function doPendingamt(val) {
        var req = Inint_AJAX();
        req.onreadystatechange = function () {
         if (req.readyState==4) {
              if (req.status==200) {
                    document.getElementById('PENDING_AMT').value="";
                   document.getElementById('PENDING_AMT').value=req.responseText; //retuen value
              }
         }
        };
        req.open("GET", "pendingamnt.php?val="+val); //make connection
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
        req.send(null); //send value
    }

I hope you understand well
Thank you in advance

A: I have solved this problem.
I have just modify the code and get sollution
Here is my modified function
function doPendingamt(val,cnt) {
        var req = Inint_AJAX();
        req.onreadystatechange = function () {
         if (req.readyState==4) {
              if (req.status==200) {
                   //document.getElementById('PENDING_AMT').value="";
                   //document.getElementById('PENDING_AMT').value=req.responseText; //retuen value

                   $('input[name=PENDING_AMT['+cnt+']]').val();
                   $('input[name=PENDING_AMT['+cnt+']]').val(req.responseText);

                   var elements = document.getElementsByClassName('purshasedocscss');

                   var totalAmt = 0;
                   var pendingAmt = 0;
                   var greater = 0;
                   for(var x=0; x < elements.length; x++){
                       if(val == elements[x].value && elements[x].value != -1){
                           if(pendingAmtTmp > pendingAmt) {
                                pendingAmt = pendingAmtTmp;
                           }
                           greater++;
                       }
                   }

                   if(greater > 1) {
                        for(var y=0; y < elements.length; y++){

                            if(val == elements[y].value && $('input[name=AMOUNT['+y+']]').val() != ''){
                                var amount      = $('input[name=AMOUNT['+y+']]').val();
                                totalAmt        = parseFloat(amount) + parseFloat(totalAmt);
                            }
                        }
                        var amt = pendingAmt - totalAmt;
                        $('input[name=PENDING_AMT['+cnt+']]').val(amt);
                   }
              }
         }
        };
        req.open("GET", "pendingamnt.php?val="+val); //make connection
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
        req.send(null); //send value
    }

Thank you who have give time for this issue.


Q: Radio Button change event not working in chrome or safari I've got some radio buttons on a page and when Yes is selected, some other controls (dropdowns and textboxes) become visible. If No is selected, they become invisible again. This is working fine in FF & IE. It does work when I use the mouse with chrome, but when I'm tabbing through the page, the controls never become visible. It's as if the change event doesn't trigger because I'm tabbing. Any ideas of what might be causing this, or how I'd go about fixing it?
The show/hide functionality is being done with JQuery.
Edit: Showing the code that is giving problems.
$("#rbtnControlYes").change(function () { $("#otherControls").show(); });

A: Found the answer to this.
Instead of using the .change event, I switched it to .click and everything worked fine.
Hope this helps someone.
Slap

A: For those not using JQuery, the onClick event is what you want.
It appears that onClick has the behavior of what we intuitively call "select". That is, onClick will capture both click events and tab events that select a radio button. onClick on Chrome
onClick has this behavior across all browsers (I've tested with IE 7-9, FF 3.6, Chrome 10, & Safari 5).


Q: Angular 6 HttpClient set param date only if its not null I am trying to pass parameter to URL. For which I am using Angular HttpParams. How do I set date param only if date is not null or undefined?
Code:
let params = new HttpParams()
   .set('Id', Id)
   .set('name', name)

if (startDate !== null) {
    params.set('startDate', startDate.toDateString());
}

if (endDate !== null) {
    params.set('endDate', endDate.toDateString());
}

A: set does not mutate the object on which it is working - it returns a new object with the new value set. You can use something like this:
let params = new HttpParams()
   .set('Id', Id)
   .set('name', name)

if (startDate != null) {
    params = params.set('startDate', startDate.toDateString());
}

if (endDate != null) {
    params = params.set('endDate', endDate.toDateString());
}

Note how the params object is being reassigned. Also note the use of != to protect against both null and undefined.

A: Instead of using the HttpParams object you can define and mutate your own object and pass it within the http call.
let requestData = {
  Id: Id,
  name: name
}
if (startDate) {
//I am assuming you are using typescript and using dot notation will throw errors
//unless you default the values
  requestData['startDate'] = startDate
}
if (endDate) {
  requestData['endDate'] = endDate
}

//Making the assumption this is a GET request
this.httpClientVariableDefinedInConstructor.get('someEndpointUrl', { params: requestData })


Q: Rails getting validation failed error, but no errors in ActiveRecord error model I am having a problem with validation errors when saving a model using save!. The ActiveRecord error model error messages are blank, so i dont know what errors are happening on a validation attempt. When I try errors.full_messages or errors.each_full according to the documentation, it should display the errors, which it doesn't.
The model I am trying to save is the Orders model (ecommerce site using Spree). When an item in the order gets deleted, update_totals! gets called which recalculates the totals, and then save! is called, which triggers the validation error (this error happens very rarely but only when I'm logged in, and I havent been able to find the cause of it). The order model has two validations in its model:
  validates_numericality_of :item_total
  validates_numericality_of :total

i recorded order.item_total.inspect, order.total.inspect, and order.errors.full_messages.inspect and got this:
Wed Jan 25 08:53:08 -0800 2012order item total: #<BigDecimal:15780c60,'0.279E2',8(16)>
Wed Jan 25 08:53:08 -0800 2012order total: #<BigDecimal:152bf410,'0.2448225E2',12(20)>
Wed Jan 25 08:53:08 -0800 2012: ERRORS SAVING ORDER:
Wed Jan 25 08:53:08 -0800 2012[]

item_total and total are stored in the mySQL database as decimal(8,2). The last line is order.errors.full_messages.inspect, which is an empty array. The validation error looks like this:
ActiveRecord::RecordInvalid (Validation failed: {{errors}}):
  vendor/extensions/mgx_core/app/models/order.rb:382:in `update_totals!'
  vendor/extensions/mgx_core/app/controllers/line_items_controller.rb:7:in `destroy'
  app/middleware/flash_session_cookie_middleware.rb:19:in `call'
  C:\Users\mgx\My Documents\Aptana Studio 3 Workspace\catalogue-spree\script\server:3
  c:/Ruby187/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.16/lib/ruby-debug-ide.rb:112:in `debug_load'
  c:/Ruby187/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.16/lib/ruby-debug-ide.rb:112:in `debug_program'
  c:/Ruby187/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.16/bin/rdebug-ide:87
  c:/Ruby187/bin/rdebug-ide:19:in `load'
  c:/Ruby187/bin/rdebug-ide:19

I guess my question is twofold:
1. Why is my activerecord errors model not saying what the validation error is?
2. How do I fix this problem? Is my item_total and total valid for saving as decimal(8,2)?
I am using rails 2.3.5 and spree 0.10.2

A: When you have before_validation declarations and if they return false then you'll get a Validation failed (ActiveRecord::RecordInvalid) message with an empty error message (if there are no other errors).
Note that before_validation callbacks must not return false (nil is okay) and this can happen by accident, e.g., if you are assigning false to a boolean attribute in the last line inside that callback method. Explicitly write return true in your callback methods to make this work (or just true at the end if your callback is a block (as noted by Jesse Wolgamott in the comments)).
UPDATE: This will no longer be an issue starting Rails 5.0, as return false will no longer halt the callback chain (throw :abort will now halt the callback chain).
UPDATE: You might also receive ActiveRecord::RecordNotSaved: Failed to save the record if a callback returns false.

A: I think the problem lies in the controller code. The order variable is set before the line item is destroyed, and is not aware it's been destroyed afterwards. This code should really be in the model:
# line_item.rb
after_destroy :update_totals!
delegate :update_totals, :to=> :order

And the controller should just destroy the line item.

A: Regarding 1. Why is my activerecord errors model not saying what the validation error is?, see if you have the gem i18n installed. If you do, try uninstalling or an earlier version of the gem i18n.
gem uninstall i18n

A: It looks to me like you are using Ruby 1.8.7. Have you tried running your app using Ruby 1.9.3?

A: When you create other register in a before_validation method, if it fails, the error will be thrown by the 'father' class, so it won't show error, just <ActiveRecord::RecordInvalid: Validation failed: > I noticed that when I got an error in my 'child' record using byebug inside before validation method

A: Throwing a reply in here as it took a bit for us to track this down. We were upgrading to Rails 5.2 and suddenly started getting this exception.
It was due to us overriding destroyed? on the model (we were soft deleting items).


Q: Shrink polygon to a specific area by offsetting I have a 2D polygon that I want to shrink by a specific offset (A) to match a certain area ratio (R) of the original polygon.
Is there a formula or algorithm for such a problem? I am interested in a simple solution for a triangle/quad but also a solution for complex polygons.
I attached an image for explanation. The original polygon is offset by A (equal-distant for each edge). A has to be chosen so that the new polygon has a specific area. In this example it should have half the area of the initial polygon.

A: Your question is very nonspecific, but here is one way to do what you are looking for, assuming I understand what you are asking. Note that this may cause an undesirable offset in position which you will have to deal with in some way. Not knowing what point you want to scale the polygon about, these solutions assume the simplest circumstances.
The reason for the square root in all of these formulas is that area tends to change with the square of linear scaling, just as volume does with the cube of linear scaling.
For general polygon:
A = sqrt(R)
for each point in polygon:
    point.x := point.x * A
    point.y := point.y * A

For circle:
A = sqrt(R)
circle.radius := circle.radius * A

For rectangle in terms of width and height:
A = sqrt(R)
rect.w := rect.w * A
rect.h := rect.h * A


Q: Fill Datatable with Variable dont work. But if i put the exact same value to a php site and request it with ajax. It works.... Why? This is in the variable "test":
{"data":[{"HistChar_ID":"4","Vorname":"Garnier","Nachname":"de
 Naplouse"},{"HistChar_ID":"2","Vorname":"Robert","Nachname":"de
 Sable"},{"HistChar_ID":"7","Vorname":"Ibn","Nachname":"Dschubair"},{"HistChar_ID":"6","Vorname":"Baha
 ad-Din","Nachname":"ibn
 Schaddad"},{"HistChar_ID":"1","Vorname":"Richard","Nachname":"L\u00f6wenherz"},{"HistChar_ID":"5","Vorname":"Wilhelm","Nachname":"von
 Montferrat"}]}

HTML:

            HistChar_ID
            Vorname
            Nachname

            HistChar_ID
            Vorname
            Nachname

An the following Code Wont fill the Datatable.
$('#example').DataTable({
    data: test,
    columns: [
        { data: 'HistChar_ID'  },
        { data: 'Vorname' },
        { data: 'Nachname' },
    ]

it throws an Error like this:

DataTables warning: table id=example - Requested unknown parameter
'HistChar_ID' for row 0, column 0. For more information about this
error, please see http://datatables.net/tn/4

I tried so much. But if i take whats inside of "test" and put it into a php and use ajax it works just fine with this.
    $('#example').DataTable({
        ajax: 'RESOURCES/PHP/Searchfield.php',
        columns: [
            { data: 'HistChar_ID' },
            { data: 'Vorname' },
            { data: 'Nachname' },

        ]

PHP/Searchfield
include 'connection.php';

$searchstuff = $_GET['Searchfield'];

$sql = "select * FROM historischercharacter WHERE Vorname LIKE '%$searchstuff%' OR Nachname LIKE '%$searchstuff%' ORDER BY Nachname" ;
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));

$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
    $emparray[] = $row;
}

echo json_encode(array('data'=>$emparray));

mysqli_close($conn);

Can someone explain me why? Is it impossible to fill the Datatable with a variable?? I just dont get it...

A: If you look at the examples in the documentation, the hard-coded array being passed into the table doesn't have the outer data property, it's just an array by itself - see https://datatables.net/examples/data_sources/js_array.html . You can see the same thing here as well: https://datatables.net/reference/option/data
The requirements when defining an AJAX data source are different. As per the example at https://datatables.net/reference/option/ajax by default you must supply an object with a "data" property as per the structure you've shown us in your question.
So it's simply that the requirements for each type of data source are different. Always read the documentation!
Demo of how to set the data source using a variable, with your variable. Note the absence of the "data" property...instead "test" is just a plain array:

var test = [{
    "HistChar_ID": "4",
    "Vorname": "Garnier",
    "Nachname": "de Naplouse"
  }, {
    "HistChar_ID": "2",
    "Vorname": "Robert",
    "Nachname": "de Sable"
  }, {
    "HistChar_ID": "7",
    "Vorname": "Ibn",
    "Nachname": "Dschubair"
  }, {
    "HistChar_ID": "6",
    "Vorname": "Baha ad-Din",
    "Nachname": "ibn Schaddad"
  }, {
    "HistChar_ID": "1",
    "Vorname": "Richard",
    "Nachname": "L\u00f6wenherz"
  }, {
    "HistChar_ID": "5",
    "Vorname": "Wilhelm",
    "Nachname": "von Montferrat"
  }];

$('#example').DataTable({
  data: test,
  columns: [{
      data: 'HistChar_ID'
    },
    {
      data: 'Vorname'
    },
    {
      data: 'Nachname'
    },
  ]
});

            HistChar_ID
            Vorname
            Nachname

            HistChar_ID
            Vorname
            Nachname

A: Here is an example using a JavaScript variable which does not require you to change the data you show in your question:
var test = { "data": [ { ... }, { ... }, ... ] };

In the above structure, each element in the array [ ... ] contains the data for one table row.
In this case, the DataTable uses the data option to specify where that array can be found:
data: test.data

Here is the runnable demo:

var test = {
    "data": [{
        "HistChar_ID": "4",
        "Vorname": "Garnier",
        "Nachname": "de Naplouse"
    }, {
        "HistChar_ID": "2",
        "Vorname": "Robert",
        "Nachname": "de Sable"
    }, {
        "HistChar_ID": "7",
        "Vorname": "Ibn",
        "Nachname": "Dschubair"
    }, {
        "HistChar_ID": "6",
        "Vorname": "Baha ad-Din",
        "Nachname": "ibn Schaddad"
    }, {
        "HistChar_ID": "1",
        "Vorname": "Richard",
        "Nachname": "L\u00f6wenherz"
    }, {
        "HistChar_ID": "5",
        "Vorname": "Wilhelm",
        "Nachname": "von Montferrat"
    }]
};

$(document).ready(function() {

$('#example').DataTable({
    data: test.data,
    columns: [
        { data: 'HistChar_ID'  },
        { data: 'Vorname' },
        { data: 'Nachname' },
    ]
} );

} );
<!doctype html>

  <meta charset="UTF-8">
  <title>Demo</title>

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
  <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">

            HistChar_ID
            Vorname
            Nachname

            HistChar_ID
            Vorname
            Nachname

JavaScript Data Sources
In the above example, the data is sourced from a JavaScript variable - so at the very least you always need to tell DataTables what the name of the JS variable is, using the data option.
And, you may also need to tell DataTables where the array of row data can be found in that variable. This is what we needed to do in the above example.
If the JavaScript variable had been structured like this (an array, not an object containing an array)...
var test = [ { ... }, { ... }, ... ];

...then in that case, we only need to use data: test in the DataTable.

Ajax Data Source
For Ajax-sourced data, things are slightly different. There is no JavaScript variable - there is only a JSON response.
By default, if that JSON response has the following structure (an array of objects called "data" - or an array of arrays)...
{ "data": [ { ... }, { ... }, ... ] }

...then you do not need to provide any additional instructions for DataTables to locate the array. It uses "data" as the default value.
Otherwise if you have a different JSON structure, you need to use the Ajax dataSrc option to specify where the array is in the JSON response.
For the above example, if you do not provide the dataSrc option, that is the same as providing the following:
ajax: {
  url: "your URL here",
  dataSrc: "data" // this is the default value - so you do not need to provide it
}

This is why your Ajax version "just works" when you only provide the URL:
ajax: 'RESOURCES/PHP/Searchfield.php'

DataTables is using the default value of data to find the array it needs.
And this is why it doesn't work when you use a JavaScript variable called test with data: test.

So, for JavaScript-sourced data, there is no default value. You always have to provide the JavaScript variable name - and maybe additional info for the location of the array in the varaible.
But for Ajax-sourced data, there is a default value (data) - and I believe this is only provided for backwards compatibility with older versions of DataTables.


Q: How to create a CAAnimation effect like moon rotates around the earth and rotates by itself at the same time in IOS? I know it is simple to create the effect making the moon circling around the earth in IOS. Suppose the moon is a CALayer object, just change the anchorPoint of this object to the earth then it will animate circling around the earth. But how to create the moon that rotate by itself at the same time? since the moon can only have one anchorPoint, seems I can not make this CALayer object rotate by itself anymore. What do you guys think? thanks.

A: You can cause the "moon" to revolve around a point by animating it along a bezier path, and at the same time animate a rotation transform. Here is a simple example,
@interface ViewController ()
@property (strong,nonatomic) UIButton *moon;
@property (strong,nonatomic) UIBezierPath *circlePath;
@end

@implementation ViewController

-(void)viewDidLoad {
    self.moon = [UIButton buttonWithType:UIButtonTypeInfoDark];
    [self.moon addTarget:self action:@selector(clickedCircleButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.moon];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    CGRect circleRect = CGRectMake(60,100,200,200);
     self.circlePath = [UIBezierPath bezierPathWithOvalInRect:circleRect];
     self.moon.center = CGPointMake(circleRect.origin.x + circleRect.size.width, circleRect.origin.y + circleRect.size.height/2.0);
}

- (void)clickedCircleButton:(UIButton *)sender {

    CAKeyframeAnimation *orbit = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    orbit.path = self.circlePath.CGPath;
    orbit.calculationMode = kCAAnimationPaced;
    orbit.duration = 4.0;
    orbit.repeatCount = CGFLOAT_MAX;
    [self.moon.layer addAnimation:orbit forKey:@"circleAnimation"];

    CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    fullRotation.fromValue = 0;
    fullRotation.byValue   = @(2.0*M_PI);
    fullRotation.duration = 4.0;
    fullRotation.repeatCount = CGFLOAT_MAX;
    [self.moon.layer addAnimation:fullRotation forKey:@"Rotate"];
}

These particular values will cause the "moon" to keep the same face toward the center like earth's moon does.

A: Use two layers.

*

*One is an invisible "arm" reaching from the earth to the moon. It does a rotation transform around its anchor point, which is the center of the earth. This causes the moon, out at the end of the "arm", to revolve around the earth.

*The other is the moon. It is a sublayer of the "arm", sitting out at the end of the arm. If you want it to rotate independently, rotate it round its anchor point, which is its own center.
(Be aware, however, that the real moon does not do this. For the real moon, the "arm" is sufficient, because the real moon rotates in sync with its own revolution around the earth - so that we see always the same face of the moon.)

A: I was looking for this kind of implementation myself.
I followed rdelmar answer and used this swift version:
class ViewController: UIViewController {

var circlePath: UIBezierPath!
var moon = UIButton(frame: CGRect(x: 10, y: 10, width: 50, height: 50))

override func viewDidLoad() {
    super.viewDidLoad()
    setup()
}

func setup() {
    let circleRect = CGRect(x: 60, y: 100, width: 200, height: 200)
    self.circlePath = UIBezierPath(ovalIn: circleRect)
    self.moon.center = CGPoint(x: circleRect.origin.x + circleRect.size.width, y: circleRect.origin.y + circleRect.size.height/2.0)
    self.moon.addTarget(self, action: #selector(didTap), for: .touchUpInside)
    moon.backgroundColor = .blue
    self.view.addSubview(moon)
}

@objc func didTap() {
    let orbit = CAKeyframeAnimation(keyPath: "position")
    orbit.path = self.circlePath.cgPath
    orbit.calculationMode = .paced
    orbit.duration = 4.0
    orbit.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
    moon.layer.add(orbit, forKey: "circleAnimation")

    let fullRotation = CABasicAnimation(keyPath: "transform.rotation.z")
    fullRotation.fromValue = 0
    fullRotation.byValue = CGFloat.pi*2
    fullRotation.duration = 4
    fullRotation.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
    moon.layer.add(orbit, forKey: "Rotate")
}

}


Q: error mysqli_fetch_array() expects parameter 1 to be mysqli_result, string given
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, string given

this is my  codes can anyone tell me what is wrong?
$result ="SELECT * FROM report" ;
if(mysqli_query($cons, $result)) {
echo("

 ID
 first_name
 last_name
 phone
 address
 email
 birthdate
 gender
 city
 dr_name

");
while($row = mysqli_fetch_array($result))
{
$ID         =$row['ID'];
$first_name =$row['first_name'];
$last_name  =$row['last_name'];
$phone      =$row['phone'];
$address    =$row['address'];
$email      =$row['email'];
$birthdate  =$row['birthdate'];
$gender     =$row['gender'];
$city       =$row['city'];
$dr_name    =$row['dr_name'];

echo "

A: Problem
You are missing how to pass the argument to mysqli_fetch_array().
Solution
Therefore, this line:
if(mysqli_query($cons, $result)) {

should be
if($res = mysqli_query($cons, $result)) { // assign the return value of mysqli_query to $res

(FWIW, I'd go with $res = mysqli_query($cons, $result); then do if($res) {.)
And then do
while($row = mysqli_fetch_array($res)) // pass $res to mysqli_fetch_array instead of the query itself

Why?
You were giving to mysqli_fetch_array() - as an argument - the string that contains your query. That's not how it works. You should pass the return value of mysqli_query() instead. Therefore, you could also write: while($row = mysqli_fetch_array(mysqli_query($cons, $result))) {} (but it's not adviced, it is just to show you how it works).

A: As mentioned in the comment, you need to set a $result from your query and use that in your loop instead.
$qry ="SELECT * FROM report";
$result = mysqli_query($cons, $qry);
if ($result){
    while($row = mysqli_fetch_array($result)){
    }
}

A: you can write like this:-
$query = mysqli_query($cons,"SELECT * FROM items WHERE id = '$id'");
if (mysqli_num_rows($query) > 0)
{
while($row = mysqli_fetch_assoc($query))
{
  $result=$row;
}
}


Q: Error cart message on Ajax My goal is to have a cart that live updates when you change the quantity's. Normally you need to press the 'update cart' button.
So I update my cart live by doing this:
require(['jquery', 'Magento_Customer/js/customer-data',
    'jquery/jquery-storageapi'], function ($) {
    // $("#submitbutton").hide();
    var form = $('form#form-validate');
    var qtyfields = $('input.qty');
    var increase = $('.meigee-arrow-right');
    var decrease = $('.meigee-arrow-left');
    increase.remove();
    decrease.remove();

    form.find(qtyfields).each(function (e) {

        $(this).change(function () {

            console.log('change detected');
            var thisfield = $(this);
            var datafield = thisfield.val();
            thisfield.attr('defaultValue', 'value');
            thisfield.html(datafield);
            TriggerAjax();

        });
    });

    function TriggerAjax() {
        $.ajax({
            url: form.attr('action'),
            data: form.serialize(),
            type: 'post',
            success: function (res) {
                form.submit();
                console.log('succes');
            },
            error: function () {
                console.log('error');
            }
        });
    }

    form.on('submit', function (e) {
        console.log('form submitted');
        e.preventDefault();
    });

    function LiveError() {
        console.log('test live error');
    }
});

And this works fine. I see the numbers change in my cart when the stock is there. The only thing is that the error message is not visible until I reload my cart page (the checkout/cart page).
Now i noticed that the form has data-mage-init='{"validation":{}}'
<form action="<?php /* @escapeNotVerified */ echo $block->getUrl('checkout/cart/updatePost') ?>"
          method="post"
          id="form-validate"
          data-mage-init='{"validation":{}}'
          class="form form-cart">

When I look closer at that Magento widget it does some kind of validation and sends it through ajax (i guess).
What I'm thinking is that it's not getting trigger until the page is reloaded so I'm not sure how to initiate this or make this happen.
Thanks in advance!

A: I tried your code and Ajax run fine but i cannot see the changes at same time. I see changes only when a page is loaded. Regarding message not showing, in my case when ajax request is going on this url:-
http://XXX/Magento2.1.6/checkout/cart/updatePost/
then it throws 302 error because updatePost execute method returns $this->_goBack().
Since we are using ajax we can modify this to return a JSON so that request is updated successfully.
For example, I modified it as
 public function execute()
{
    if (!$this->_formKeyValidator->validate($this->getRequest())) {
        return $this->resultRedirectFactory->create()->setPath('*/*/');
    }

    $updateAction = (string)$this->getRequest()->getParam('update_cart_action');

    switch ($updateAction) {
        case 'empty_cart':
            $this->_emptyShoppingCart();
            break;
        case 'update_qty':
            $this->_updateShoppingCart();
            break;
        default:
            $this->_updateShoppingCart();
    }

    echo 55; exit();/* can be anything which server correct ajax response*/
}

And it works and shows me error message though my price and other data are currently not updating(Might be this could be the reason):-

A: As error messages are already set to page messages from class "Magento\Checkout\Controller\Cart\UpdatePost::_updateShoppingCart()" catch part, you can get it in ajax success by using below code
var messages = $.cookieStorage.get('mage-messages');
if (!_.isEmpty(messages)) {
    customerData.set('messages', {messages: messages});
    $.cookieStorage.set('mage-messages', '');
}

//reload messages section
var messages_section = ['messages'];
//customerData.invalidate(messages_sections);
customerData.reload(messages_section);


Q: Restify & Bluebird - how to pass an error from a catch block to restify error handler? I am working on a node js server, and using bluebird for promise implementation. I understand how to use promises, but my problem is what to do with the error returned from a promise. I tried the simple solution - just trowing the error again - but bluebird catch it, and the client never receive a response. Bellow is a demo code, to illustrate my question:
var restify = require('restify');
var Promise = require('bluebird');

var server = restify.createServer({
  name: 'myapp',
  version: '1.0.0'
});

server.get('/', function (req, res, next) {
    new Promise(function(resolve, reject){
        reject(new Error());
    }).then(function(res){
        res.send('hello');
    }).catch(function(e){
        throw e;
    });
});

server.on('uncaughtException', function (req, res, route, error) {
    console.log('error');
});

server.listen(7070, function () {
  console.log('%s listening at %s', server.name, server.url);
});

I am looking for a way to somehow pass the error to restify, so it will raise the uncaughtException event and I could handle it like any other uncaught exception. After searching this a bit, I found that I can simply do something like next(new InternalServerError()) and restify will raise an event for this specific error, but this is look a bit weird to me, so I am looking for a better way.

A: Here's a PoC that will rethrow any "possibly unhandled rejections". These will subsequently trigger Restify's uncaughtException event:
var Promise = require('bluebird');
var restify = require('restify');
var server  = restify.createServer();

server.listen(3000);

Promise.onPossiblyUnhandledRejection(function(err) {
  throw err;
});

server.get('/', function (req, res, next) {
  Promise.reject(new Error('xxx')); // no `.catch()` needed
});

server.on('uncaughtException', function (req, res, route, err) {
  console.log('uncaught error', err);
  return res.send(500, 'foo');
});


Q: Firebug freezes Firefox on showing errors from FirePHP I have problem with debugging one of my projects. Every notice/warning/error is caught by FirePHP, and set with headers to browser. I catch all those errors with enabled Firebug, and everything's showing right in console:

One of function of FirePHP with Firebug is to show details about those errors. And here's the problem - when i hover error with my mouse, Firefox freezes. CPU usage is very low, but memory consumption rises to 1,5-2GB. Cure is to kill FF, or wait 3-5 minutes till it suggests to kill frozen script

chrome://firephp/content/viewer/panel.js:601

Do anyone struggles with similar issue?
Versions:

*

*Firefox 36.0.1

*Firebug 2.0.8

*FirePHP 0.7.4

UPDATE:
Ok, so i found why is it freezing. Data sent to Firebug contains all i18n messages from my app (as i'm using SF1.0 - it is in context) - and it simply is too large to quickly parse it to viewer. I dug up into my code, and even disabling sending all context from my PHP, doesn't disable context to show up in Variable viewer.

A: This may not be the most elegant solution, but I would try (for a test) disabling firePHP and use instead a logging tool such as log4php and have it log your exceptions where and when they might be thrown.
Thus, if you're not doing so already.. use try and catch blocks and in the catch blocks, log your exception to a file that you'd declare in the config/instantiation of log4php.
Just a suggestion.


Q: Error: useHref() may be used only in the context of a  component. in register,js Good afternoon, I am creating an app in reactjs and all the routes work fine, only the register user gives the error Error: useHref() may be used only in the context of a  component.I am using firebase for this, the login with google and user and password works 100%, thanks
register.js code
import { push } from "firebase/database";
import React, { useEffect, useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { Link, Route, useHistory } from "react-router-dom";

import {
  auth,
  registerWithEmailAndPassword,
  signInWithGoogle,
} from "../config/firebase";
function Register() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [user, loading, error] = useAuthState(auth);
  const register = () => {
    if (!name) alert("Please enter name");
    registerWithEmailAndPassword(name, email, password);
  };
  useEffect(() => {
    if (loading) return;
    if (user) Route.push("/dashboard");
  }, [user, loading]);
  return (

        <input
          type="text"
          className="register__textBox"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Full Name"
        />
        <input
          type="text"
          className="register__textBox"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="E-mail Address"
        />
        <input
          type="password"
          className="register__textBox"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Password"
        />
        <button className="register__btn" onClick={register}>
          Register
        </button>
        <button
          className="register__btn register__google"
          onClick={signInWithGoogle}
        >
          Register with Google
        </button>

          Already have an account? <Link to="/">Login</Link> now.

  );
}
export default Register;

A: You forgot to wrap your React App within BrowserRouter or some router. Go to index.js in src folder. Wrap it like this.
<BrowserRouter>
   <App />
</BrowserRouter>

Then, add some Route. For example, like this.
 <BrowserRouter>
       <Routes>
           <Route element={<Home/>} path={"/"} />
           <Route element={<Another />} path={"/another}/>
       </Routes>
    </BrowserRouter>


Q: XSLT replace an element that exists inside another element value I am new to XSLT (using XSLT v1.0) and I have the following input:
<SUMMARY>
<TITLE>Lorem ipsum dolor <QUOTE ID="replace with this string"/> sit vel eu.
</TITLE>
<P> Lorem ipsum dolor <QUOTE ID="replace with this string"/> sit vel eu. </P>
</SUMMARY>

<REFERENCE>
<TI>Lorem ipsum dolor <QUOTE ID="replace with this string"/> sit vel eu.
</TI>
<P> Lorem ipsum dolor <QUOTE ID="replace with this string"/> sit vel eu. </P>
</REFERENCE>

How could I replace all the occurrences of the element QUOTE inside my XML input, with a String that is the value of the QUOTE/ID attribute.

A: Add to the identity transform a special template to handle QUOTE:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="QUOTE">
      <xsl:value-of select="@ID"/>
  </xsl:template>

</xsl:stylesheet>

The identity transformation will copy everything to the output XML, and the special QUOTE template will copy over the value of its @ID attribute in place of the QUOTE element.


Q: Visual C++, multiple for loops using same iterator name, visible outside of scope in debug mode I'm using Visual Studio Express 2013 and have multiple for loops where I use the same name for the iterator, like so:
for (int i = 0; i < 10; i++) {
  // do something
}
....
for (int i = 0; i < 10; i++) {
  // do something else
}

When I step through in debug mode, after leaving the first for loop the first 'i' remains visible in the Locals window at its final value 10, even though it has gone out of scope. Then I enter the second for loop and I now have two i's showing (albeit with different values). It's a slight annoyance because I'll break somewhere on another condition and I can't immediately see what the value of i is. I can get around that by just declaring 'i' once outside the iterator scope:
int i;
...
for (i = 0; i < 10; i++) {
  // do something
}
...
for (i = 0; i < 10; i++) {
  // do something else
}

But it still bothers me because it seems inconsistent. I would expect to see the same behavior as this, where the first 'i' disappears from the Locals window once it goes out of scope:
{
  int i = 0;}
}
...
{
  int i = 1;
}

I want to know whether it's just a Microsoft thing, or if I don't properly understand scoping in for loops ...

A: Nice catch.
To me, it sounds like a compiler bug more or less. There is an option in VC to select to "Force Conformance In For Loop Scope" so that the for loop variable goes out of scope outside for loop.
However, that doesn't fix the issue you mentioned in the debugger. Regardless of which option you select, both variables are there in the debugger, which appears to be confusing.
The only way to distinguish between them is that out-of-scope i should have value 0xcccccccc in debug mode. This should be compiler specific, and WinDbg handles it in a different way, as mentioned in the following article.
What I tried: VC2008, VC2012
There is a good article well experimenting this issue.

A: MSVC has a special compiler flag that can affect the scoping of int i in your examples: /Zc:forScope.
It's on by default, but the debugger is probably set up to accommodate for it to be turned off with /Zc:forScope- which would make the following code valid (even though it's not standards-compliant):
{
    for (int i=0; i < 10; ++i)
    {
        // Do something
    }

    for(i=0; i < 10; ++i)
    {
        // Do something else
    }
}

Alternatively, if you've accidentally turned it off, your code is not working as you (and the C++ standard) expect, but then you'd probably get a warning on redeclaring i.

A: There is an option in Visual Studio that controls whether the scope of variables defined in a for loop are visible beyond the for loop. It's called /Zc:forScope. When you use /Zc:forScope-, you get the behavior you described. To change the behavior to conform to C++ stanards, you have to use /Zc:forScope
More information can be found at MSDN Website: /Zc:forScope (Force Conformance in for Loop Scope).


Q: How to reach my main form controlls from my UserControl I have Balloon user control that opens in the tray when my application is minimyze.
So i created simple Button on this Balloon:
public partial class ApplicationBalloon : UserControl
{
    private void btnStart_Click(object sender, RoutedEventArgs e)
    {

    }
}

When this event is fired i want to click on specific button in my main form so i can i reach my main form controlls from this UserControl ?
EDIT
In my main form after the c'tor:
    applicationBalloon = new ApplicationBalloon();
    applicationBalloon.BalloonClicked += applicationBalloon_BalloonClicked;

And in my User Control:
public partial class ApplicationBalloon : UserControl
{
    public event EventHandler<RoutedEventArgs> BalloonClicked;
    public ApplicationBalloon()
    {
        InitializeComponent();
    }

    private void btnStart_Click(object sender, RoutedEventArgs e)
    {
        if (BalloonClicked != null)
            BalloonClicked(sender, e);
    }
}

The btnStart_Click is after my application is running and allthough BalloonClicked is still null.

A: Add an event to your balloon class, handle the click in your balloon class and pass the arguments up to whoever attaches to your event.
In your balloon class:
public partial class ApplicationBalloon : UserControl
{
    public event EventHandler<RoutedEventArgs> BalloonClicked;

    private void OnButtonClicked(object sender, RoutedEventArgs e)
    {
        if (BalloonClicked != null)
            BalloonClicked(sender, e);
    }
}

You can now add a handler to your main form attached to BalloonClicked.

A: Just access it with:
Application.Current.MainWindow

And cast it to whatever your main window type is.


Q: How to add value between tags using XElement? I have looked a bunch of XML samples using XDocument and XElement but they all seem to have self closing tags like <To Name="John Smith"/>. I need to do the following:
<To Type="C">John Smith</To>

I thought the following would work and tried to look at the object model of the Linq.XML class, but I'm off just a tad (see line below that is not working)
new XElement("To", new XAttribute("Type", "C")).SetValue("John Smith")

Any assistance on how to get the XML formed properly is appreciated, thanks!

A: How about
  new XElement("To", new XAttribute("Type", "C"), "John Smith")

A: I'd use:
new XElement("To", new XAttribute("Type", "C"), "John Smith");

Any plain text content you provide within the XElement constructor ends up as a text node.
You can call SetValue separately of course, but as it doesn't return anything, you'll need to store a reference to the element in a variable first.


Q: Error org.json.JSONException: Value  Error of type java.lang.String cannot be converted to JSONObject I have a Android app about Public Transportation, and I have a PHP script that connects to mySQL database. This is the main.java
package com.chera.trans;

import com.chera.trans.R;

 import android.os.Bundle;
 import android.app.Activity;
 import android.content.Intent;
 import android.view.Menu;
 import android.view.MenuInflater;
 import android.view.MenuItem;

  public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.menu_main, menu);
      return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
    case R.id.traseu2:
        Intent traseu2 = new Intent(this, Traseu2.class);
        this.startActivity(traseu2);
        break;
    case R.id.traseu401:
        Intent traseu401 = new Intent(this, Traseu401.class);
        this.startActivity(traseu401);
        break;
    default:
        return super.onOptionsItemSelected(item);
    }

    return true;
}

}
And this is the code for Traseu2.java
package com.chera.trans;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

 import org.apache.http.HttpResponse;
 import org.apache.http.client.ClientProtocolException;
  import org.apache.http.client.HttpClient;
   import org.apache.http.client.methods.HttpPost;
  import org.apache.http.impl.client.DefaultHttpClient;
  import org.json.JSONArray;
   import org.json.JSONException;
    import org.json.JSONObject;

  import com.chera.trans.R;

import android.os.AsyncTask;
import android.os.Bundle;
 import android.app.Activity;
   import android.content.Intent;
    import android.view.Menu;
    import android.view.MenuInflater;
  import android.view.MenuItem;
  import android.widget.ListView;
 import android.widget.SimpleAdapter;
  import android.widget.Toast;

 public class Traseu2 extends Activity {
 private String jsonResult;
 private String url = "http://transploiesti.tk/2.php";
 private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.traseu2);
    listView = (ListView) findViewById(R.id.listView1);
    accessWebService();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.menu_main, menu);
      return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
    case R.id.traseu2:
        Intent traseu2 = new Intent(this, Traseu2.class);
        this.startActivity(traseu2);
        break;
    case R.id.traseu401:
        Intent traseu401 = new Intent(this, Traseu401.class);
        this.startActivity(traseu401);
        break;
    default:
        return super.onOptionsItemSelected(item);
    }

    return true;
}

 // Async Task to access the web
 private class JsonReadTask extends AsyncTask<String, Void, String> {
  @Override
  protected String doInBackground(String... params) {
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(params[0]);
   try {
    HttpResponse response = httpclient.execute(httppost);
    jsonResult = inputStreamToString(
      response.getEntity().getContent()).toString();
   }

   catch (ClientProtocolException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
   return null;
  }

  private StringBuilder inputStreamToString(InputStream is) {
   String rLine = "";
   StringBuilder answer = new StringBuilder();
   BufferedReader rd = new BufferedReader(new InputStreamReader(is));

   try {
    while ((rLine = rd.readLine()) != null) {
     answer.append(rLine);
    }
   }

   catch (IOException e) {
    // e.printStackTrace();
    Toast.makeText(getApplicationContext(),
      "Error..." + e.toString(), Toast.LENGTH_LONG).show();
   }
   return answer;
  }

  @Override
  protected void onPostExecute(String result) {
   ListDrwaer();
  }
 }// end async task

 public void accessWebService() {
  JsonReadTask task = new JsonReadTask();
  // passes values for the urls string array
  task.execute(new String[] { url });
 }

 // build hash set for list view
 public void ListDrwaer() {
  List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

  try {
   JSONObject jsonResponse = new JSONObject(jsonResult);
   JSONArray jsonMainNode = jsonResponse.optJSONArray("traseudoi");

   for (int i = 0; i < jsonMainNode.length(); i++) {
    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
    String name = jsonChildNode.optString("Statie");
    String number = jsonChildNode.optString("Oraplecare");
    String outPut = "Autobuzul pleaca din " + name + " la ora " + number;
    employeeList.add(createEmployee("employees", outPut));
   }
  } catch (JSONException e) {
   Toast.makeText(getApplicationContext(), "Error" + e.toString(),
     Toast.LENGTH_SHORT).show();
  }

  SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
    android.R.layout.simple_list_item_1,
    new String[] { "employees" }, new int[] { android.R.id.text1 });
  listView.setAdapter(simpleAdapter);
 }

 private HashMap<String, String> createEmployee(String name, String number) {
  HashMap<String, String> employeeNameNo = new HashMap<String, String>();
  employeeNameNo.put(name, number);
  return employeeNameNo;
 }

}
` Why I receive this error when I m running the app? Thanks!

A: HTML is not JSON, and it can not be parsed into JSONObjects. The top answer for org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject is pretty good at explaining this further.


Q: android-tab new contents while viewing it? Some apps have this feature, that when a new post is added while the app is in the foreground it shows this view:

Can anybody offer an article or blog post to get this view with animation and all that?
I can do it by myself, but I want it to look professional.
Any advice would be appreciated.


Q: Is setting Roles in JWT a best practice? I am considering to use JWT. In the jwt.io example I am seeing the following information in the payload data:
"admin": true

Admin can be considered as a Role, hence my question. Is setting the role in the token payload a habitual/good practice? Given that roles can be dynamically modified, I'm quite interrogative.

A: Nothing stops you from creating claims to store extra information in your token if they can be useful for your client.
However I would rely on JWT only for authentication (who the caller is). If you need to perform authorization (what the caller can do), look up the caller roles/permissions from your persistent storage to get the most updated value.
For short-lived tokens (for example, when propagating authentication and authorization in a microservices cluster), I find it useful to have the roles in the token.

A: As mentioned here, ASP.NET Core will automatically detect any roles mentioned in the JWT:
{
  "iss": "http://www.jerriepelser.com",
  "aud": "blog-readers",
  "sub": "123456",
  "exp": 1499863217,
  "roles": ["Admin", "SuperUser"]
}

and 'map' them to ASP.NET Roles which are commonly used to secure certain parts of your application.
[Authorize(Roles = "Admin")]
public class SettingsController : Controller

The server which is giving out (and signing) the JWT is commonly called an authorization server and not just an authentication server, so it makes sense to include role information (or scope) in the JWT, even though they're not registered claims.

A: The official JWT site explicitly mentions "authorization" (in contrast to "authentication") as a usecase for JWTs:

When should you use JSON Web Tokens?
Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

That being said, from a security-perspective you should think twice whether you really want to include roles or permissions in the token.
(The text below can be understood as a more "in-depth" follow up to the rather short-kept accepted answer)
Once you created and signed the token you grant the permission until the token expires. But what if you granted admin permissions by accident? Until the token expires, somebody is now operating on your site with permissions that were assigned by mistake.
Some people might argue that the token is short-lived, but this is not a strong argument given the amount of harm a person can do in short time. Some other people advocate to maintain a separate blacklist database table for tokens, which solves the problem of invalidating tokens, but adds some kind of session-state tracking to the backend, because you now need to keep track of all current sessions that are out there – so you would then have to make a db-call to the blacklist every time a request arrives to make sure it is not blacklisted yet. One may argue that this defeats the purpose of "putting the roles into the JWT to avoid an extra db-call" in the first place, since you just traded the extra "roles db-call" for an extra "blacklist db-call".
So instead of adding authorization claims to the token, you could keep information about user roles and permissions in your auth-server's db over which you have full control at any time (e.g. to revoke a certain permission for a user). If a request arrives, you fetch the current roles from the auth-server (or wherever you store your permissions).
By the way, if you have a look at the list of public claims registered by the IANA, you will see that these claims evolve around authentication and are not dealing with what the user is allowed to do (authorization).
So in summary you can...

*

*add roles to your JWT if (a) convenience is important to you and (b) you want to avoid extra database calls to fetch permissions and (c) do not care about small time windows in which a person has rights assigned he shouldn't have and (d) you do not care about the (slight) increase in the JWT's payload size resulting from adding the permissions.

*add roles to your JWT and use a blacklist if (a) you want to prevent any time windows in which a person has rights assigned he shouldn't have and (b) accept that this comes at the cost of making a request to a blacklist for every incoming request and (c) you do not care about the (slight) increase in the JWT's payload size resulting from adding the permissions.

*not add roles to your JWT and fetch them on demand if (a) you want to prevent any time windows in which a person has rights assigned he shouldn't have or (b) avoid the overhead of a blacklist or (c) avoid increasing the size of your JWT payload to increase slightly and (d) if you accept that this comes at the cost of sometimes/always querying the roles on incoming requests.


Q: what is missing for DocumentNode function to show text in datagridview? What i´m trying to do is to use the documentnode method to find a specific table from the internet and put it into datagridview. My code can be seen below:
`
List<string> list = new List<string>();
DataTable dt1 = new DataTable();

var table = doc.DocumentNode.SelectNodes("xpath link")
       .Descendants("tr")
       .Where(tr=>tr.Elements("td").Count()>1)
       .Select(td => td.InnerText.Trim())
       .ToList();

foreach (var tables in table)
{ list.Add(tables.ToString());}

dataGridView1.DataSource = list

`
The result I get in the table is a list of numbers instead of text (datagridview table). As I have tried to see it the text actually appears I changed the foreach with the following code:
`
foreach (var tables in table)
{
 list.Add(tables.ToString());
richTextBox1.Text += tables;
}

`
The result I get from the change is a string of the table in richTextBox1 but still a table of numbers in datagridview1 richtextbox1 text. This means I´m getting the right table from the internet and its being loaded correctly but i´m still missing something for the datagridview1 as I get a list of numbers instead of text that is being shown in richtextbox1. I followed this up by changing the DocumentNode function with removing parts in the .select part of the code and the datagridview1 stilled showed numbers (I added for example .ToString, .ToList() etc.).
What exactly have I missed in my code that makes this happen and should I have added something else to make it show the text instead of numbers?
Edit:
New code.
`
List<string> list = new List<string>();
DataTable dt1 = new DataTable();
dt1.Columns.Add("td", typeof(int));

var table = doc.DocumentNode.SelectNodes("//div[@id=\"cr_cashflow\"]/div[2]/div/table")
.Descendants("tr")
.Select(td => td.InnerText.Trim())
.ToList();

foreach (var tables in table)
{
dt1.Rows.Add(new object[] { int.Parse(tables) });
}
dataGridView1.DataSource= dt1;

`

A: Try something like this
List<string> list = new List<string>();
DataTable dt1 = new DataTable();
dt1.Columns.Add("td",typeof(int));
var rows = doc.DocumentNode.SelectNodes("xpath link")
       .Descendants("tr")
       .Where(tr=>tr.Elements("td").Count()>1)
       .Select(td => td.InnerText.Trim())
       .ToList();

foreach (var row in rows)
{
    dt.Rows.Add(new object[] { int.Parse(row)});
}


Q: javascript syntax for new objects and prototypes I'm femiliar with OOP from PHP / JAVA but i'm a newbie in JS prototype objects.
My question is: I found that there are 4 ways (probably more) to instantiate a new object:
1. var d = Object.create(Object.prototype);
2. var d = {};
3. var d = new Object();
4.
var d = function(){};
d.prototype = {a:xxx, b:yyy};

what is the different between the four in regards to the prototype (as i understand prototype is the main Object constructor which all object inherits from).
Hope I got it right....thanks,
Danny


Q: Align link to bottom of div and center it I'm trying to make a link stick to the bottom center of a div and have it be centered.
So far I've come up with this:
http://jsfiddle.net/r494Lx0r/2/
div.container {
position: relative;
height: 110px;
width: 120px;
border: dashed 1px red;
}

div.container div.text {
position: absolute;
bottom: 0px;
border: solid 1px black;
}

Now how do I make it so that it's centered? I've tried adding text-align:center; and margin:0 auto; to the container but neither of those do anything.
Does anyone know how to do this?

A: UPDATE add text-algin: center to the parent to center the anchor and set border: solid 1px black; to your anchor:

div.container {
 position: relative;
 height: 110px;
 width: 120px;
 border: dashed 1px red;
}

div.container div.text {
 position: absolute;
 bottom: 0px;
 right: 0;
    left: 0;
    text-align: center;
}

a{border: solid 1px black;}

  Google.com

Add Width: 100% and text-align: center

div.container {
 position: relative;
 height: 110px;
 width: 120px;
 border: dashed 1px red;
}

div.container div.text {
 position: absolute;
 bottom: 0px;
    text-align: center;
    width:100%;
 border: solid 1px black;
}

  Google.com

or left: 0;, right: 0; and text-align: center;

div.container {
 position: relative;
 height: 110px;
 width: 120px;
 border: dashed 1px red;
}

div.container div.text {
 position: absolute;
 bottom: 0px;
    left: 0;
    right: 0;
    text-align: center;
 border: solid 1px black;
}

  Google.com

or you can combine `margin-left: 50%;` and `transform: translate(-50%)`

div.container {
 position: relative;
 height: 110px;
 width: 120px;
 border: dashed 1px red
}

div.container div.text {
 position: absolute;
 bottom: 0px;
 border: solid 1px black;
    margin-left: 50%;
    -webkit-transform: translate(-50%);
    -moz-transform: translate(-50%);
    transform: translate(-50%)
}

  Google.com

A: display:block;
margin:auto;

makes elements centered. So you could edit your code to become:
div.container div.text {
bottom: 0px;
border: solid 1px black;
display:block;
margin:auto;
}

A: .text{ width: 100%; text-align: auto; }

The text wrapping div will then be as wide as its container, so text align will work as expected.  The reason text-align isn't working for you on your current code is because the "text" div is only as wide as the link, therefore centering its contents does nothing.

A: PROVIDED the link is the bottom/last element in the div-
add this to the div:
text-align: center; //centers the text

and then set the link to:
margin-top: auto; // pushes the text down to the bottom

worked in my case.
Simple and quick, but only works provided your link is the last element in the div.


Q: Finding specific data in Oracle Tables I needed to find a value for a column in my oracle database but i don't know which
table or column it's stored in
How can I search for a specific or like %% data as I do in
select * from SYS.dba_source

is there a table like that
Column Name ID  Data Type             Null?         Comments

OWNER   1   VARCHAR2 (30 Byte)       Y
NAME    2   VARCHAR2 (30 Byte)       Y    Name of the object
TYPE    3   VARCHAR2 (12 Byte)       Y

Type of the object:
"TYPE", "TYPE BODY", "PROCEDURE", "FUNCTION",
"PACKAGE", "PACKAGE BODY" or "JAVA SOURCE"

LINE    4   NUMBER                  Y    Line number of this line of source
TEXT    5   VARCHAR2 (4000 Byte)    Y    Source text

A: LINK: pl/sq to find any data in a schema
Imagine, there are a few tables in your schema and you want to find a specific value in all columns within these tables. Ideally, there would be an sql function like
select * from * where any(column) = 'value';

Unfortunately, there is no such function.
However, a PL/SQL function can be written that does that. The following function iterates over all character columns in all tables of the current schema and tries to find val in them.
  create or replace function find_in_schema(val varchar2)
    return varchar2 is
      v_old_table user_tab_columns.table_name%type;
      v_where     Varchar2(4000);
      v_first_col boolean := true;
      type rc     is ref cursor;
      c           rc;
      v_rowid     varchar2(20);

    begin
      for r in (
        select
          t.*
        from
          user_tab_cols t, user_all_tables a
        where t.table_name = a.table_name
          and t.data_type like '%CHAR%'
        order by t.table_name) loop

        if v_old_table is null then
          v_old_table := r.table_name;
        end if;

        if v_old_table <> r.table_name then
          v_first_col := true;

          -- dbms_output.put_line('searching ' || v_old_table);

          open c for 'select rowid from "' || v_old_table || '" ' || v_where;

          fetch c into v_rowid;
          loop
            exit when c%notfound;
            dbms_output.put_line('  rowid: ' || v_rowid || ' in ' || v_old_table);
            fetch c into v_rowid;
          end loop;

          v_old_table := r.table_name;
        end if;

        if v_first_col then
          v_where := ' where ' || r.column_name || ' like ''%' || val || '%''';
          v_first_col := false;
        else
          v_where := v_where || ' or ' || r.column_name || ' like ''%' || val || '%''';
        end if;

      end loop;
      return 'Success';
    end;


Q: Minizinc, how to create a map or a dictionary datastructure I have a simple question regarding the Minizinc's syntax. My input .dzn file contain a set of 2 dimentional arrays (approximately up to 30 arrays), declared as follows:
rates_index_0 = array2d(1..3, 1..501, [ 15, 20, 23, ....
rates_index_12 = array2d(1..3, 1..501, [ 21, 24, 27, ....
...

note: index numbers have gaps in them (e.g., 12 -> 20)
In my model, I need to use one of these arrays depending on the value of the variable. In common programming language I would solve it using a map or a dictionary datastructure. But in Minizinc I am hardcoding this in the following way:
function var int: get_rate(int: index, var int: load, int: dc_size) =

        if index == 0 then
          rates_index_0[dc_size, load]
        else if index == 12 then
          rates_index_12[dc_size, load]
        else if index == 16 then
          rates_index_16[dc_size, load]
        else if index == 20 then
          rates_index_20[dc_size, load]
        else
          assert(false, "unknown index", 0)
        endif endif endif endif;

The one obvious problem with this code is that I need to change model each time I change input. Is there a better way how I can code this in a generic way?
Thanks!

A: In an more abstract way a map-structure is nothing more than a function mapping inputs of a certain type to an array. A map can thus be replaced by a array and a function. (The difference being you will have to define the function yourself)
Before I get started with the rest I would like to point out that if your model compiles generally fast, you might want to try a triple array without the function, rates_index = array3d(0..60, 1..3, 1..501, [ 15, 20, 23, ..... This will cost more memory, but will make the model more flexible.
The general way of using a map-structure would be to define a function map_index, that maps your input, in this case integers, to the index of the array, also integers. This means that we can then define a extra level array to point to the right one: rates_index = array3d(0..nr_arrays, 1..3, 1..501, ..... This means that the content of get_rates can then be: rates_index[map_index(index), dc_size, load].
The function map_index itself in its simplest form would contain another version of your if-then-else statements:
function int: map_index(int: index) =
    if index == 0 then
        0
    else if index == 12 then
        1
    else if index == 16 then
        2
    else if index == 20 then
        3
    else
        assert(false, "unknown index", 0)
    endif endif endif endif;

However you can make it dynamic by generating an extra array containing the array number for each index, putting -1 for all arrays that are not available. For your example the mapping would look like this: array[0..20] of int: mapping = [0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, 2, -1, -1, -1, 3];. The map_index function could then dynamically be defined as:
function int: map_index(int: index) =
    mapping[index];


Q: How can users use their email accts to look for friends on my site? I'm working on a new social networking site and I want to give users a way to:
1) Automatically scan my site for people they already know (email/linkedin/facebook/etc)
2) Provide users with the option of inviting their friends to join the site
It seems like many of these tools have their own api, but in most cases it doesn't look like I would be able to get a unique id (the email, basically).  Are there other tools out there I could/should look at?

A: As for Facebook, unfortunately this is not possible using email since users may choose not to share their real email with you.
One way, for Facebook, is to store the Facebook user id (you should be doing this anyway) and retrieve the newly registered user friends' ids and check if any of these ids present in your DB.

A: I implemented this on one of my sites.  When users register for an account, I require an email address.  I give them an option to find their email accounts (gmail, hotmail, aol, and yahoo all have oauth services you can use to get contacts).  I also give them the option for LinkedIn, Facebook, and Twitter.  This doesn't work as well as those 3 social networks won't disclose email addresses (and rightfully so).  So each user that authenticates, I log their id from that service.  Then I get the id's of their friends, and see if any of those friends have associated their account with my site.  The key for this to work is to encourage your users to associate those accounts.


Q: Tensorflow distributed inference I have a large model (GPT-J 6B) and two 16G GPUs (V100 with no NVLink). I would like to do inference (generation). GPT-J needs 24G memory, so I need to split the model across my two GPUs.
For me, simplicity is much more important than maximizing utilization/throughput.
What is the easiest way to distribute the network?  Is it possible to put first half of the network on one GPU and the second half on the other? (pipeline-parallel essentially)