text:
Q: Why nested nuxt link in vuetify doesn't work? I am using NuxtJS with Vuetify and I have the following (shortened) component
<template>
  <v-card nuxt :to="`/article/${id}`">
    <v-card-actions>
      <v-btn active-class="no-active" text nuxt :to="`/newspaper/${newspaper.latName}`">
        <v-icon>mdi-text-box</v-icon>
        {{ newspaper.araName }}
      </v-btn>
      <v-btn text class="mr-2">
        <v-icon>mdi-clock-outline</v-icon>
        {{ since }}
      </v-btn>
    </v-card-actions>
  </v-card>
</template>

This gives me the following warning in the browser console:

[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example, nesting block-level elements inside, or missing. Bailing hydration and performing full client-side render.

but the page still works and navigation still works too. If I replace one of the nuxt link with a function triggering a router push the warning goes away.
Why does this happen?
EDIT: This is how I use this component
<template>
  <span>
    <ArticleCard
      v-for="(article, i) in articles"
      :key="i"
      v-bind="article"
    ></ArticleCard>
  </span>
</template>

A: You do have 2 things here:

*

*DOM hydration issue, here is a related question with all the available details. Feel free to read it and come back to me after if it is really not working. But mainly, inspect the DOM with your devtools and try to see what is generated/hydrated.

*you're probably not using the :to prop properly here. Here is the Vuetify documentation which is basically saying that you can check Vue router's :to prop. This one is to be used like :to="'home'" or :to="{ name: 'name' }". I'm not sure of the content of buttonLink but be sure that this is following the required object/string.


text:
Q: What is the best way to cache XML feeds locally? I have a XML feed which contains 1000+ records of properties (rent, sale).
Currently I am calling this feed 16x on homepage, always returning only 3 properties for specific criteria like 3 new house, 3 new flats, etc, 5 recommended house, 5 recommended flats etc.
This scenario was working well for 7 months whilst there was 200+ properties and only 100-200 views a day. It is now getting to stage where I have 700+ visits a day and over 1000+ properties and downloading 16 feeds separately just to show homepage is getting slower and traffic is getting massively larger.
Therefore I would like to cache these streams, I would like only my 'robot' to directly download streams from source and all visitors to use my local copy to make things much quicker and decrease traffic load massively.
I dont have a problem downloading XML locally and locally call files to show data. But I would like to know how to solve possible issues like:

*

*not showing data to clients because robot is updating XML files and original file would be overwritten and empty whilst loading new data

*using XML file as local backup, means that if source server is offline homepage would be still working and loading

*making sure that I wont lock data for clients in such way that robot would be unable to update files

My first toughts would be to work with 2 xml files for every stream, one which would be shown to clients and one which would be downloaded. If download is correct then downloaded XML would be used as live data and other one deleted. Some kind of incremental marking with one file working as file holding name of actual data.
Is there any way how to cache these XML files so it would do something similar? Really the main issue is to have bulletproof solution so clients wont see error pages or empty results.
Thanks.

A: Use the caching options built into HttpWebResponse. This lets you programatically choose between obtaining straight from cache (ignoring freshness), ignoring the cache, forcing the cache to be refreshed, forcing the cache to be revalidated and the normal behaviour of using the cache if it's considered fresh according to the original response's age information, and otherwise revalidating it.
Even if you've really specific caching requirements that need to go beyond that, build it on top of doing HTTP caching properly, rather than as a complete replacement.
If you do need to manage your own cache of the XML streams, then normal file locking and if really necessary, .NET ReaderWriterLockSlims should suffice to keep different threads from messing each other up. One possibility to remove the risk of contention that is too high, is to default to direct access in the case of cache contention. Consider that caching is ultimately an optimisation (conceptually you are getting the file "from the server", caching just makes this happen in a more efficient manner). Hence, if you fail to quickly obtain a read-lock, you can revert to downloading directly. This in turn reduces the wait that can happen for the write lock (because pending locks won't stack up over time while a write lock is requested). In practice it probably won't happen very often, but it will save you from the risk of unacceptable contention building up around one file and bringing the whole system down.

A: I'm going to start by assuming that you don't own code that produces the source XML feed? Because if you do, I'd look at adding some specific support for the queries you want to run.
I had a similar issue with a third-party feed and built a job that runs a few times a day, downloads the feed, parses it, and stores the results locally in a database.
You need to do a bit of comparison each time you update the database, and only add new records and delete old records, but it ensures that you always have data to feed to your clients and the database works around simple issues like file locking.
Then I'd look at a simple service layer to expose the data in your local store.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the recommended way to persist the data in background task? [UWP/W/WP apps] The question is quite simple, but I seriously couldn't find any sample that would demonstrate something I'm trying to achieve, maybe it's me who is didn't get the concept of background tasks in uwp applications (or windows / windows phone 8).
I'm creating an application that is polling some data (traffic incidents) and would like to be able to notify the user about the closes ones even if he is not using the application. So I reckon I would use the background task. (I hope I get that part right).
So in the background task, which I've set to run on timer of 15 minutes, under the condition of "InternetAvailable", I fetch the data asynchronously and once it's done, I'm completing the deferral object as it's required. All works ok.
The question is, what object shall I use in order to persist the data so I could read the data once the application is opened?
I've tried the WinJS.Application.sessionState but that gets lost once the application is ready (opened).
I've tried the Windows.Storage.ApplicationData.current.localSettings but it says there is a type mismatch, apparently I'm trying to put in there the object, if String is expected (I reckon)...
So does anyone know what is the best practice here ?
Thank you

A: You have full acess to the WinRT API, so you can write a file (and read the same file once the application is opened):
function saveData(dataObj) {
    var applicationData = Windows.Storage.ApplicationData.current;
    var localFolder = applicationData.localFolder;
    return localFolder.createFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (sampleFile) {
            return Windows.Storage.FileIO.writeTextAsync(sampleFile, JSON.stringify(dataObj));
    });
}


text:
Q: Cannot import MaterialTimeControlModule after installation I am trying to install https://github.com/SteveDunlap13/MaterialTimeControl under Angular 6. The installation succeeds without errors but I still cannot import the MaterialTimeControlModule.
All I can see is in my node_modules/ this is the only directory which is not marked as "orange" so I guess that means there's something wrong?

What am I missing here or could this be due to my recent update from Angular 5 to Angular 6?

A: As you write in comments under your question:

I am following this stackblitz example. I add it to my imports in my
  app.module.ts

As you can see, in that example,in app.module.ts there is import MaterialTimeControlModule from.... SRC directory (not node_modules) !
This mean that you should create similar materia-time-control.module.ts file in your SRC directory and import it in app.module.ts in similar way. You probably should also create similar src/time-control directory (may be with som local changes depend on your particular project).


text:
Q: Not able to solve No_Pubkey Tried update using:
sudo apt-get update

got following response:
Ign:1 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:2 http://dl.google.com/linux/chrome/deb stable Release
Get:3 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]
Hit:5 http://in.archive.ubuntu.com/ubuntu bionic InRelease
Hit:6 http://ppa.launchpad.net/umang/indicator-stickynotes/ubuntu bionic InRelease
Hit:7 http://in.archive.ubuntu.com/ubuntu bionic-updates InRelease
Get:8 http://in.archive.ubuntu.com/ubuntu bionic-backports InRelease [74.6 kB]
Get:9 https://deb.torproject.org/torproject.org bionic InRelease [4,244 B]
Err:9 https://deb.torproject.org/torproject.org bionic InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 74A941BA219EC810
Reading package lists... Done
W: GPG error: https://deb.torproject.org/torproject.org bionic InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 74A941BA219EC810
E: The repository 'https://deb.torproject.org/torproject.org bionic InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

Then I tried:
~$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 74A941BA219EC810

And got
Executing: /tmp/apt-key-gpghome.LvVh1YzHpU/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 74A941BA219EC810
^[[A^[[Bgpg: packet(13) too large
gpg: read_block: read error: Invalid packet
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0

What am I missing?

A: For some reasons it seems keyserver is taking longer than expected for some reason at least for me. You can try importing key for tor using:
curl https://deb.torproject.org/torproject.org/A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89.asc | gpg --import
gpg --export A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89 | apt-key add -


text:
Q: Reading special column while avoiding some special characters in text file in C/C++ Can somebody help me about this please? :
I have a text file in this form:
"1.101511000000E+02","-3.066300000000E+01"
"8.328840000000E+01","-7.020080000000E+01"
"1.053746000000E+02","-4.622800000000E+01"
"1.314320000000E+01","-7.866200000000E+01"
"9.876160000000E+01","-5.844720000000E+01"
"3.129990000000E+01","-7.919930000000E+01"
"7.152530000000E+01","-7.527770000000E+01"
"2.849310000000E+01","-7.933210000000E+01"
"7.602290000000E+01","-7.410480000000E+01"`

it has 4003 lines. I want to read these columns like avoiding the characters: '"' and ','.
Then I read the signs + or - and recognize the 'E' to make the power and write my results to another file and then use it later. I give you an example of what I need:
1.101511000000   +02    -3.066300000000   +01
And then what I have to do is for example once I get the first column :
1.101511000000
and when I know that it's power 2 I do this:
1.101511000000 x 10²
and what I will write to my new file is:
110.1511     -30.663
83.2884      -70.2
105.3746     -46.228
etc.
So the main questions are:
1) How can I read this text file and avoiding these special characters?
2)finding the power written in form e.g E+02?
3)Doing the calculations?
4) avoiding all redundant 000 in float?
5) putting the results at the same time in a new file?
I appreciate you all in advance, but please consider that fact which this is very urgent and important for me now.
Mojdeh

A: You can use fscanf to read the two numbers with their respective exponents.
Something like this:
fscanf(pFile, "\"%f\", \"%f\"", &number1, &number2);

Then all you have to do is write it back to the second file using fprintf, like this:
fprintf(pFile2, "%g %g", number1, number2);

The %g format prints the number using the shortest representation.
For more information on these functions go to http://www.cplusplus.com/reference/cstdio/fprintf/.


text:
Q: SharpZipLib create an archive with an in-memory string and download as an attachment I use DotNetZip to create a zip archive with an in memory string and download it as an attachment with the following code.
byte[] formXml = UTF8Encoding.Default.GetBytes("<form><pkg>Test1</pkg></form>");
byte[] formHtml = UTF8Encoding.Default.GetBytes("Test2");

ZipFile zipFile = new ZipFile();
zipFile.AddEntry("Form.xml", formXml);
zipFile.AddEntry("Form.html", formHtml);
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("content-disposition", "attachment; filename=FormsPackage.zip");
zipFile.Save(Response.OutputStream);
zipFile.Dispose();

Now I have a requirement to do the same with SharpZipLib. How can I do it ? Does SharpZipLib support adding files as array of bytes ?

A: Try below
MemoryStream msFormXml = new MemoryStream(UTF8Encoding.Default.GetBytes("<form><pkg>Test1</pkg></form>"));
MemoryStream msFormHTML = new MemoryStream(UTF8Encoding.Default.GetBytes("Test2"));

MemoryStream outputMemStream = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);

zipStream.SetLevel(3); //0-9, 9 being the highest level of compression

ZipEntry xmlEntry = new ZipEntry("Form.xml");
xmlEntry.DateTime = DateTime.Now;
 zipStream.PutNextEntry(xmlEntry);
StreamUtils.Copy(msFormXml, zipStream, new byte[4096]);
zipStream.CloseEntry();

ZipEntry htmlEntry = new ZipEntry("Form.html");
htmlEntry.DateTime = DateTime.Now;
zipStream.PutNextEntry(htmlEntry);
StreamUtils.Copy(msFormHTML, zipStream, new byte[4096]);
zipStream.CloseEntry();

zipStream.IsStreamOwner = false;
zipStream.Close();

outputMemStream.Position = 0;

byte[] byteArray = outputMemStream.ToArray();

Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=FormsPackage.zip");
Response.AppendHeader("Content-Length", byteArray.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(byteArray);


text:
Q: Getting errors in C++ while compiling my code which uses curl I found same codes to read datas from a web page for C++. It was like that:
#include <iostream>
#include <string>
#include <C:\curl\curl.h>
// Right path, I am sure.

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

int main(void)
{
    CURL *curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);

        std::cout << readBuffer << std::endl;
    }
    return 0;
}

But it does not work as it is expected. Here is the error messages:
1>------ Build started: Project: deneme, Configuration: Debug Win32 ------
1>  deneme.cpp
1>deneme.obj : error LNK2019: unresolved external symbol __imp__curl_easy_cleanup referenced in function _main
1>deneme.obj : error LNK2019: unresolved external symbol __imp__curl_easy_perform referenced in function _main
1>deneme.obj : error LNK2019: unresolved external symbol __imp__curl_easy_setopt referenced in function _main
1>deneme.obj : error LNK2019: unresolved external symbol __imp__curl_easy_init referenced in function _main
1>C:\Users\nazif\Documents\Visual Studio 2010\Projects\deneme\Debug\deneme.exe : fatal error LNK1120: 4 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

How can I fix this?
Basicly, I want to get content of a certain web page with using curl in my C++ code.

A: The #include <C:\curl\curl.h> just includes the relevant function prototypes etc. What you also have to do is update your project settings to tell the linker to link to the appropriate curl library.
Since you're using Visual Studio, right-click on your project and select properties. Then go to Configuration Properties/Linker. Then go to to Linker -> Input and enter the name of you lib file (there's probably a curl.lib in C:\curl\) in the Additional Dependencies field.

A: Follow these instructions

MSVC 6 IDE

A minimal VC++ 6.0 reference workspace (vc6curl.dsw) is available with the
     source distribution archive to allow proper building of the two included
     projects, the libcurl library and the curl tool.
1) Open the vs/vc6/vc6curl.dsw workspace with MSVC6's IDE.
2) Select 'Build' from top menu.
3) Select 'Batch Build' from dropdown menu.
4) Make sure that the eight project configurations are 'checked'.
5) Click on the 'Build' button.
6) Once the eight project configurations are built you are done.
Dynamic and static libcurl libraries are built in debug and release flavours,
     and can be located each one in its own subdirectory, dll-debug, dll-release,
     lib-debug and lib-release, all of them below the 'vs/vc6/lib' subdirectory.
In the same way four curl executables are created, each using its respective
     library. The resulting curl executables are located in its own subdirectory,
     dll-debug, dll-release, lib-debug and lib-release, below 'vs/vc6/src' subdir.
These reference VC++ 6.0 configurations are generated using the dynamic CRT.
Intentionally, these reference VC++ 6.0 projects and configurations don't use
     third party libraries, such as OpenSSL or Zlib, to allow proper compilation
     and configuration for all new users without further requirements.
If you need something more 'involved' you might adjust them for your own use,
     or explore the world of makefiles described above 'MSVC from command line'.

Once it's done building, you'll have a .lib file in one of the folders


text:
Q: Titanium - connect to socket.io Server I am trying to make an simple Chat Applikation with socket.io and Titanium for IOS/Android.
I was able to get the example Skript from socket.io running on my local machine.
I can send and receive messages over my browsers.
But i cant connect with my IOS App i build in Titanium.
I dont get the connect status in the console.
Does someone knows what i am doing wrong. Or have i forgotten something?
I have tried it with the Titanium.Network.Socket.TCP function:
var hostname = '127.0.0.1';

    var clientSocket = Ti.Network.Socket.createTCP({
        host : hostname,
        port : 3000,
        connected : function(e) {
            Ti.API.info('Client socket connected!');
            Ti.Stream.pump(e.socket, pumpCallback, 1024, true);
            e.socket.write(Ti.createBuffer({
                value : 'A message from a connecting socket.'
            }));
        },
        error : function(e) {
            Ti.API.info('Error (' + e.errorCode + '): ' + e.error);
        }
    });

    function writeCallback(e) {
        Ti.API.info('Successfully wrote to socket.');
    }

    function pumpCallback(e) {
        // Has the remote socket closed its end?
        if (e.bytesProcessed < 0) {
            Ti.API.info("Closing client socket.");
            clientSocket.close();
            return;
        }
        try {
            if (e.buffer) {
                var received = e.buffer.toString();
                Ti.API.info('Received: ' + received);
            } else {
                Ti.API.error('Error: read callback called with no buffer!');
            }
        } catch (ex) {
            Ti.API.error(ex);
            }
        }

Ti.API.info("Setting timer to connect.");
        setTimeout(function(e) {
            Ti.API.info("Calling connect on client socket.");
            clientSocket.connect();
        }, 500);

And the code from my server:
    var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
    console.log('a user connected');
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Output in Titanium:
[INFO] :   Setting timer to connect.
[INFO] :   Calling connect on client socket.
[INFO] :   Client socket connected!
[INFO] :   Closing client socket.

A: Socket.IO goes hand by hand with socket.io.js file which runs in the browser. You can't just replace this file with simple TCP requests.
You may try to use libraries (like this one and this one) that allow you to create Socket.IO client on Objective-C.


text:
Q: Data structure and algorithms for 1D velocity model using layers? This is for a geophysical analysis program I am creating. I already have code to do all this, but I am looking for inspirations and ideas (good datastructures and algorithms).
What I want to model:

*

*Velocity as a function of depth (z)

*The model is built up from multiple layers (<10)

*

*Every layer is accessible by an index going from 0 for the top most layer to n for the bottom most layer

*Every layer has velocity as a linear function of depth (gradient a_k and axis intercept b_k of the kth layer)

*Every layer has a top and bottom depth (z_k-1 and z_k)

*The model is complete, there is no space between layers. The point directly between two layers belongs to the lower layer

Requirements:

*

*Get velocity at an arbitrary depth within the model. This will be done on the order of 1k to 10k times, so it should be well optimized.

*Access to the top and bottom depths, gradients and intercepts of a layer by the layer index

What I have so far:
I have working Python code where every layer is saved as a numpy array with the values of z_k (bottom depth), z_k-1 (top depth), a_k (velocity gradient) and b_k (axis intercept). To evaluate the model at a certain depth, I get the layer index (, use that to get the parameters of the layer and pass them to a function that evaluates the linear velocity gradient.

A: So you have piecewise linear dependence, where z-coordinates of pieces ends go irrregular, and want to get function value at given z.
Note that there is no sense to use binary search for 10 pieces (3-4 rounds of BS might be slower than 9 simple comparisons).
But what precision have your depth queries? Note that you can store a table both for 1-meter resolution and for 1 millimeter too -  only 10^7 entries provide O(1) access to any precalculated velocity value
For limited number of pieces it is possible to make long formula (involving integer division) but results perhaps should be slower.
Example for arbitrary three-pieces polyline with border points 2 and 4.5:
f = f0 + 0.2*int(z/2.0)*(z-2.0) + 0.03*int(z/4.5)*(z-4.5)


text:
Q: SDK Version Issue.This app was built with the iOS 14.5 SDK ERROR ITMS-90725: "SDK Version Issue. This app was built with the iOS 14.5 SDK. All iOS apps submitted to the App Store must be built with the iOS 15 SDK or later, included in Xcode 13 or later.
My current version is macOs Big Sur version(11.4)
and my xcode version(12.5.1)

A: You need XCode 13 to use iOS 15 SDK. Simply update your XCode and MacOS (if necessary), then build the app again.
After updating XCode, your iOS SDK will be automatically updated.
Instruction for Older macOS:

*

*Use this patch and upgrade your macOS https://github.com/Ben216k/Patched-Sur

*After the upgrade, you can install XCode 13 on your older mac.

*Here you can see all the supported mac lists: https://bensova.gitbook.io/big-sur/supported-macs

A: Below are steps I followed to solve the same issue in the same context:

*

*Upgrade macOs Big Sur -> macOs Monterey v12.4

*Update Xcode 12.x -> Xcode 13.x or later
Note: Upgrade could take some minutes. Hence, be patient


text:
Q: One table two model i have posts table
id
type enum(A,Q)
title
content
and i need controllers questions_controller and answer_controller to use
please lead the right way to
1-
make 2 models (question and answer) and use 'posts' as model's table
2-
use post model in questions_controller and answer_controller

A: For me, it should be one table has one model
So better use
$uses = array('Post'); in your controllers.
Update:
As far I understood you want to filter the data depending from the type column. Actually your db model is wrong, because except if they are totally unrelated your answers need to belong to the question. This mean you need an extra column parent_id which will determine what is the parent node (question) and child nodes (answers).
If we have this assumption, then you can set a relation in the model like:
class Post extends AppModel {
   ...
   var $belongsTo = array(
      'Parent' => array('className' => 'Post','foreignKey' => 'parent_id', 'conditions' => 'Parent.parent_id IS NOT NULL')
   );
   ...
}

So you automatically have Post and Post->Parent. But I think that it would be better to have 2 tables - one which holds the questions and another the answers.


text:
Q: Animation is not working properly? I want to translate an imagebutton to another position(position to another imagebutton) via translate animation. I have both of their positions. The animation methods I have are all uses relative position changes, but I am interested in Absolute translation. Is there any method to do that in Android?
 public void startAnimationFindChant(View view) {
            int[] locationSource = new int[2];
            int[] locationDestination = new int[2];
            view.geLocationOnScreen(locationSource);
             Log.d("locationSource",locationSource[0]+" "+locationSource[1]);
            ImageButton findachant1 = (ImageButton) findViewById(R.id.findachanticon1);

            findachant1.getLocationOnScreen(locationDestination);
            Log.d("locationDestination",locationDestination[0]+" "+locationDestination[1]);

            TranslateAnimation animation = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                    Animation.ABSOLUTE, locationSource[1], Animation.ABSOLUTE,
                    locationDestination[1]);
            animation.setFillAfter(true);
            view.startAnimation(animation);
        }

A: public void doSlideUp(View view) {
    LinearLayout myView = (LinearLayout) findViewById(R.id.content_area);
    Animation slideUp = setLayoutAnim_slideup();
    myView.startAnimation(slideUp);

}

public void doSlideDown(View view) {
    RelativeLayout myView = (RelativeLayout) findViewById(R.id.content_area1);
    Animation slideDown = setLayoutAnim_slidedown();
    myView.startAnimation(slideDown);
}

public Animation setLayoutAnim_slidedown() {

    AnimationSet set = new AnimationSet(true);

    Animation animation = new TranslateAnimation(
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, -1.0f,
            Animation.RELATIVE_TO_SELF, 0.0f);
    animation.setDuration(2000);
    animation.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

        }
    });
    set.addAnimation(animation);

    LayoutAnimationController controller = new LayoutAnimationController(
            set, 0.25f);

    return animation;
}

public Animation setLayoutAnim_slideup() {

    AnimationSet set = new AnimationSet(true);

    Animation animation = new TranslateAnimation(
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, -1.0f);
    animation.setDuration(2000);
    animation.setAnimationListener(new AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {

        }
    });
    set.addAnimation(animation);
    LayoutAnimationController controller = new LayoutAnimationController(
            set, 0.25f);
    return animation;
}

Try this and change the value of animation x asix to y axis as you required.

A: I have made one simple class for TranslateAnimation between two position using ObjectAnimator -
private void translateAnimateView(View source, View target,
        AnimatorListener listener) {
    ObjectAnimator animator = ObjectAnimator.ofFloat(source,
            "translationY", 0, target.getTop() - source.getTop());
    animator.addListener(listener);

    animator.setDuration(1000);
    animator.start();
}

This method accepts threee argument, source view, target view and listener(can be null). The source will be animated to reach target view. I have added just Y translation, but you can actually include x translation too.
This way you can have translation using absolute positions. You can anyways use the top coordinate instead of view though.


text:
Q: Inapplicability of Gauss' mean value theorem in an integration What is the value of $$\int_0^{2\pi}\ln|i+2e^{ix}|dx$$
At first glance I thought of applying Gauss mean value theorem, but this is not applicable here as $\ln|z|$ is not analytic at $0$, which belongs in the region $|z-i|<2$.
How one can approach this one? Any help is appreciated.

A: There is a beautiful (and theoretically very important) generalization of Gauss' mean value theorem, it is called the Jensen's formula. Given that you know Gauss' mean value theorem you can look up the proof of Jensen in Chapter 5 of Stein-Shakarachi's Complex Analysis.
Jensen's Formula: Let $\Omega$ be an open set that contains the closure of a disc $D_R$ and suppose that $f$ is holomorphic in $Ω$, $f (0)\neq 0$, and $f$ vanishes
nowhere on the circle $C_R$ . If $z_1 , . . . , z_N$ denote the zeros of $f$ inside the
disc (counted with multiplicities), then $$\log|f(0)|=\sum_{i=1}^{N} \log\Bigg(\frac{|z_k|}{R}\Bigg)+\frac{1}{2\pi}\int_{0}^{2\pi}\log|f(Re^{i\theta})|d\theta$$
You have to use Jensen here, because unfortunately the function $f(z)=z+i$ has a root in $|z|<2$, and $\log|.|$ of it won't satisfy the hypothesis of Gauss' mean value theorem unless we make some clever manipulations.
Now apply the above for $f(z)=z+i$, then we have that
$$\log|i|=\log|1/2|+\frac{1}{2\pi}\int_{0}^{2\pi}\log|2e^{i\theta}+i|d\theta$$ which immediately gives $$\int_{0}^{2\pi}\log|2e^{i\theta}+i|d\theta=2\pi\log(2).$$

A: Too long for a comment, but using $e^{i\theta}=\cos\theta+i\sin\theta$ we have
$$|i+2\cos(x)+2i\sin(x)|=\sqrt{4\cos^2 x+(1+2\sin x)^2}=\sqrt{4\cos^2x+1+4\sin^2x+4\sin x}$$
so that
$$I=\frac{1}{2}\int_0^{2\pi}\ln(5+4\sin x)dx=\frac{1}{2}\int_0^{2\pi}\ln(4)dx+\frac{1}{2}\int_0^{2\pi}\ln\left(\frac{5}{4}+\sin x\right)dx.$$
Hence
$$I=2\pi\log(2)+\frac{1}{2}\int_0^{2\pi}\ln\left(\frac{5}{4}+\sin x\right)dx=2\pi\log 2.$$
The only way I could show the integral to vanish was using the power series for $\log(1+z)$,
$$\int_0^{2\pi}\ln\left(\frac{5}{4}\left(1+\frac{4}{5}\sin x\right)\right)dx=2\pi\ln(5/4)+\int_0^{2\pi}\ln\left(1+\frac{4}{5}\sin x\right)dx=J.$$
Assuming we can switch integral and infinite sum, and  since $4/5|\sin x|<1$, then the integral becomes
$$-\sum_{k=1}^\infty\frac{(-1)^k}{k}\frac{4^k}{5^k}\int_0^{2\pi}\sin^k xdx=-\frac{1}{2}\sum_{k=1}^\infty\frac{1}{k}\frac{4^{2k}}{5^{2k}}\frac{\pi  \cdot\left(\frac{3}{2}\right)_{k-1}}{\Gamma (k+1)}=-2\pi\log(5/4),$$
hence $J=0$.


text:
Q: coovachilli + freeradius, how to check how many users are currently login? I installed CoovaChilli (AC) + freeradius in Ubuntu 10.10 successfully. How could I check how many user has already login and still remain active ?

A: I make possible this with this script or add-on, in his last version v2.0 Final operative functional, make possible say maxim number of guest, only a user for account, mac-ban ip-mac, mac-ip, list of user and connections and more features that your user do not know never. This add-on called Absoloom can be found at
http://bbs.belchi.org/BPI/descarga.php?code=54943
Link´s version change whit time, but you can ever found  the last version of this script in http://bbs.belchi.org into prog-bbs section
I made another release more compact, in the same link full of features
http://bbs.belchi.org/foro/viewtopic.php?f=2


text:
Q: Closest features from a mouse click – altering selection if a feature has already been found I have a working code that selects 4 closest points from a mouse click and creates a convex hull using the selection.
def canvasReleaseEvent(self, mouseEvent):
    """
    Each time the mouse is clicked on the map canvas, perform
    the following tasks:
        Loop through all visible vector point layers and for each:
            Ensure no features are selected
            Determine the distance of the closest features in the layer to the mouse click
            Keep track of the layer id and id of the closest feature
            Select the ids of the closest features and draw a hull convex using them """

    layerData = []

    for layer in self.canvas.layers():

        if layer.geometryType() != QGis.Point:

            # Ignore this layer as it's not a vector
            continue

        if layer.featureCount() == 0:
            # There are no features - skip
            continue

        layer.removeSelection()

        # Determine the location of the click in real-world coords
        layerPoint = self.toLayerCoordinates( layer, mouseEvent.pos() )
        shortestDistance = float("inf")
        closestFeatureId = -1

        for f in layer.getFeatures():
            dist = f.geometry().distance( QgsGeometry.fromPoint( layerPoint) )
            shortestDistance = dist
            closestFeatureId = f.id()

            info = (layer, closestFeatureId, shortestDistance)
            layerData.append(info)

        if not len(layerData) > 0:
            # Looks like no vector layers were found - do nothing
            return

        # Sort the layer information by shortest distance
        layerData.sort( key=lambda element: element[2] )
        selected_fid = []
        feat_geom = []
        for (layer, closestFeatureId, shortestDistance) in layerData:
            if len(selected_fid) < 4:
                selected_fid.append((layer, closestFeatureId, shortestDistance))
                points = layer.select(closestFeatureId)
            else:
                break

        # Convert selected features to list of QgsPoints
        selected_features = layer.selectedFeatures()
        for i in selected_features:
           geomp = i.geometry()
           f_geomp = geomp.asPoint()
           feat_geom.append(f_geomp)

        # Convert list of QgsPoints to multipoint geometry
        wkt = 'MULTIPOINT('
        for point in feat_geom:
            x = point.x()
            y = point.y()
            wkt += '({} {}), '.format(x, y)
        wkt = wkt[:-1] + ')'
        print(wkt)
        # Create convex hull from nearest selected points (multipoint geometry)
        multipoint = QgsGeometry.fromWkt(wkt)
        convexhull = multipoint.convexHull()

        #create memory layer if it doesn't exists or get it if it exists
        ly = None
        for layer in QgsMapLayerRegistry.instance().mapLayers().values():
            if layer.name() == 'rejon':
                ly = layer
        if ly is None:
            ly = QgsVectorLayer('Polygon?crs=epsg:27700', 'rejon', "memory")
            QgsMapLayerRegistry.instance().addMapLayers([ly])

        pr = ly.dataProvider()
        ly.startEditing()

        #add features and save changes
        poly = QgsFeature()
        poly.setGeometry(convexhull)
        pr.addFeatures([poly])
        ly.commitChanges()

Next step would to make sure that the same points are not used again with each mouse click to select closest points and create a convex hull. The idea is to create a set of convex hulls using each point only once. Operator has to be able to delete a polygon and use these points again, so the distinction if a point has already been used has to be made with relation to intersection with convex hull. Something like this:

*

*Check if (and which) points are within a polygon

I took care of that with this:
        intersections = []
        point_layer = QgsMapLayerRegistry.instance().mapLayersByName( 'flood_depth_points' )[0]
        polygon_layer = QgsMapLayerRegistry.instance().mapLayersByName( 'rejon' )[0]

        for m in point_layer.getFeatures():
            for n in polygon_layer.getFeatures():
                if polygon_layer.featureCount() == 0:
            # There are no features - skip
                    continue
                if m.geometry().buffer(1,0).intersects(n.geometry()):
                    intersections.append(m.id())
                    break
        print(len(intersections))
        print(intersections)

*If yes, alter the selection of closest points

*If no, select points and create a convex hull.

I don't know how to, based on that, alter selection of the closest points.
UPDATE:
I got what I wanted by storing id's of points that intersect with existing polygons in intersections list:
        polygon_layer = QgsMapLayerRegistry.instance().mapLayersByName( 'rejon' )[0]

        intersections = []
        for m in layer.getFeatures():
            for n in polygon_layer.getFeatures():
                if polygon_layer.featureCount() == 0:
            # There are no features - skip
                    continue
                if m.geometry().buffer(1,0).intersects(n.geometry()):
                    inter_attrs = m.id()
                    inf = (inter_attrs)
                    intersections.append(inf)
                    break

and then checking if points' id's that the script iterates through after a mouse click exist in a said list before appending the point's id to layerData:
        for f in layer.getFeatures():
            dist = f.geometry().distance( QgsGeometry.fromPoint( layerPoint) )
            shortestDistance = dist

            # check if a point has already been used to create a polygon
            if f.id() not in intersections:
                closestFeatureId = f.id()
            info = (layer, closestFeatureId, shortestDistance)
            layerData.append(info)


text:
Q: Copying features from one attribute table to another using QGIS I am struggling with copying the data from one attribute data table to another.
I have a few columns in my data attribute table, which I want to update. I can do it one by one, but its a long process, as I have about 150 records.

I decided, than it will be quicker if I do it in Excel instead, then import them into QGIS and replace the data in existing attribute data table.

I decided to do it in the following steps:
 1. Export attribute data table to .csv
 2. Make autofill in Excel
 3. Import the new attribute data table to the QGIS again
As an import I used option: Layer-Add Layer - Add delimited text layer.
After loading layer I have it own attribute layer, which I would like to copy to the attribute layer of my existing layer as per image below:

1 - my comma delimited layer imported
2 - my existing shapefile layer, where I would like to replace the attribute layer from this 1st one.
I found some solutions here:
Joining data from Excel to attribute table in QGIS without creating duplicates?
and here:
How to copy information from Excel into QGIS Attribute-Table?
but they don't really solve my issue.
I wish I could use the table joining option, but it looks like the differ columns are to be added instead to replace all with the same names.
Can anyone help me to autofill the attribute data table or fetch it from Excel?

A: Use a formula in QGIS to achieve the same thing.  Select the features you want either in the map or in the table view and then click on the calculate field button (abbacus icon) and select the field you want to update then input your forumla in the expression field.  This is MUCH easier and safer than fiddling about with Excel and table joins.
You can even select specific rows based on their current data to edit in this way.  Use the little E button in the table view and write an expression to select (say all rows where "surveyor" is null)

A: There are more elegant ways to do this with joins, etc., but as an ad-hoc one off, one simple approach that should work is:

*

*Export the original layer as a csv, but making sure under Layer Options you get the geometry exported AS_WKT. Your csv file should now consist of one line per feature, with the feature attributes as column, plus an extra first column called WKT representing the feature geometry as a text string in your chosen CRS.

*You or others can change, even add/subtract rows, in Excel. Keep the column names (=attribute names) unchanged. You can theoretically change the geometry by editing the WKT string, but this is unlikely to be useful.

*Import the edited csv as delimited text, making sure the importer Geometry Definition is set to WKT and pointed at the WKT field (which should be automatic). Make sure the geometry CRS is the same used for the export.

*Re-export the imported csv layer in your desired spatial file format (shapefile if you must, or into a geopackage or whatever), probably the same as the original format.

*Use the changeLayerSource plug-in to repoint the original layer at the new file from the previous step. If you indeed did not change the layer names, your styling etc will be preserved.
The above will implicitly (by sliding the new file in place of the old file) replace all of the old features with the edited ones, and so won't create duplicates. However, it also carries risks - you could munge stuff you didn't intend to touch if you're careless. If you need to be fancier, for instance you want to treat new features, updated features, and deleted features differently, then you will have to creatively use joins, or SQL.
The important elements for success above are to handhold QGIS to make sure the geometry is exported and then reimported, to make sure the CRS stays the same, and to ensure the data attribute names / column labels are unchanged.


text:
Q: Transimpedance Amplifiers on PCB I have several transimpedance amplifiers on my board, and I want to avoid the need for a negative power supply, but I can't see any way around it (except for running the current through a resistor but I dont want to load the circuit like that).
At the moment I've been using negative potential to avoid the need for two op amps per channel, but this is also not desirable, is there any way to have a TIA setup without a negative supply?
Cheers
EDIT: I should elaborate, the elements being read are thermistors. Each thermistor is excited by a buffer, the current through the thermistor is then read out by the TIA.

A: I'd do this as a comment, but it will be too long, so bear with me.
First, what you are doing is (at heart) a resistance measurement. Restricting yourself to thinking in terms of current is a potential source of confusion. We call this an XY problem. That is, you want to do X, and you think you MUST do it via Y, and so you ask for help with Y. Which is fine as long as you really must do Y, and not so great otherwise.
Now, about temperature. You are apparently committed to thermistors. The first thing you need to realize about temperature is that it changes very, very slowly (seconds timescale). There are exceptions, but these usually involve things like high-temperature ablation of heat shields and such. Most materials have sufficiently high thermal capacity and low thermal propagation rates that if you want to change the core temperature quickly, and needing 200 kHz measurement bandwidth counts as very quickly indeed, then you have to apply so much thermal power to the surface that you'll burn it away. Look - heat just doesn't propagate that quickly through most materials, even good thermal conductors. The fact that you seem to want to measure temperature at 200 kHz suggests very strongly that you have hold of the wrong end of an XY problem.
Now, let's say you are thinking about thermistors. And I do mean thinking. What sort of temperature range do you need? Thermistors have a wildly nonlinear response, so they are incapable of both sensitivity and wide temperature range. That is, assuming a NTC thermistor, as temperature rises the resistance rises even more quickly, and the current drops appropriately, so at the high end of the range you'll get current response much smaller per degree than at the low end.
Except for high-precision measurements, which are of necessity restricted to a fairly small temperature range, the standard thermistor circuit looks like

simulate this circuit – Schematic created using CircuitLab
VREF can be something as simple as a low-voltage zener diode, but the details are determined by your system accuracy requirements.
R1 is normally set to approximately the thermistor resistance at the bottom of the temperature range.
C1 is used for noise filtering, and since thermistors are usually used in the kilohm range it can be quite large, and the resulting low bandwidth can often handle quite large amounts of noise, so long as it occurs at higher frequencies.
Also, while not shown, if the temperature sensor is mounted off the pcb and connected via wires, a good idea is to put a resistor (say 1k to 10k) between the thermistor and the op amp/capacitor. This will tend to protect the op amp in case somebody plugs the wrong wire into the wrong hole while installing the external thermistor. Oh yes, and did I mention the virtues of connecting with twisted pair wiring?
If you feed the output to an ADC, your temperature resolution will be determined by the ADC resolution (and accuracy) as well as your temperature range. It will be very good at low temperatures and get progressively worse as the temperature goes up. The tradeoff is up to you.
If very high precision is needed, you should look into platinum RTDs, which you can think of as a special variety of PTC thermistors. They are very stable and accurate, and they can be used over large temperature ranges. Of course, nothing comes free or easy, and the cost is that they are not very sensitive, so you need to take care with your conditioning circuitry.


text:
Q: dataTable.js:65 Uncaught TypeError: Cannot read property 'aDataSort' of undefined? i am using dataTable in my UI, when i am assigning values to it the Following error is occurring
Uncaught TypeError: Cannot read property 'aDataSort' of undefined
at W (dataTable.js:65)
at ya (dataTable.js:70)
at e (dataTable.js:91)
at HTMLTableElement.<anonymous> (dataTable.js:93)
at Function.each (jquery-3.1.1.js:368)
at jQuery.fn.init.each (jquery-3.1.1.js:157)
at jQuery.fn.init.m [as dataTable] (dataTable.js:82)
at Object.success (isevaEnquirySearch.html:122)
at fire (jquery-3.1.1.js:3305)
at Object.fireWith [as resolveWith] (jquery-3.1.1.js:3435)

and my code looks like this
 $("#tblData").dataTable().fnDestroy();
            $('#tblData').dataTable({
                data : response,

                                    columns : [

                                               {    'data'  :   ' date' },
                                                {   'data'  :    ' source1' },
                                                {   'data'  :     'source2  '},
                                                {   'data'  :     'callon'  },
                                                {   'data'  :     'callby'  },
                                                {   'data'  :     'name'    },
                                                {   'data'  :     'sbiaccountsmsSentCheck'  },
                                                {   'data'  :     'sbiaccountsmsSentDate'   },
                                                {   'data'  :     'number1' },
                                                {   'data'  :     'formFilledUpCheck'   },
                                                {   'data'  :     'formFilledUpDate'    },
                                                {   'data'  :     'number2' },
                                                {   'data'  :     'formCouriredCheck'   },
                                                {   'data'  :     'formCouriredDate'    },
                                                {   'data'  :     'email1'  },
                                                {   'data'  :     'formReciCheck'   },
                                                {   'data'  :     'formReciDate'    },
                                                {   'data'  :     'email2'  },
                                                {   'data'  :     'payreciCheck'    },
                                                {   'data'  :     'payreciDate' },
                                                {   'data'  :     'pan' },
                                                {   'data'  :     'remarks'
    },

                                               ],

                                    }) ;

if i remove  $("#tblData").dataTable().fnDestroy(); this line from the code
its getting executed but the sorting and search fields are not working and the following exceptions is coming
DataTables warning: table id=tblData - Requested unknown parameter ' date' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4

i am not able to trace it can any one help me


text:
Q: Would it be possible to Merge 2 onEdit Google Script? Would it possible to merge them in one script as I don't know much about coding and would also be possible to add the username/editor's name automatically in the next cell when someone made an edit to the sheet?**
Tried pasting the code here but I am having a hard time doing it.
Here's what I am working on: https://docs.google.com/spreadsheets/d/16NBcSAyeUgVQVc4MfWJLSBBN_GqzP9YmdQPAf5oPJuI/edit?usp=sharing

A: Yes, it's possible
Just rename your two functions to something else then onEdit and call them both from a single onEdit function.
Sample:
function onEdit(e){
  one(e);
  two(e);
}
function one(e){
  ...
}
function two(e){
  ...
}


text:
Q: How to correctly set env variables in oh-my-zsh I am new to use oh-my-zsh and couldnt figure out where can I add a new env variable which we usually add in .zshrc file. Now the new zshrc file(after installing oh-my-zsh) does not show any of my already added env variables also.
I am using macbook(m1/apple) chip with oh-my-zsh. How or where can I add a new env variable. For example before using oh-my-zsh, I used to add the following lines in ~./zshrc and source the file/open a new terminal to reflect the changes.
eval "$(~/.rbenv/bin/rbenv init - zsh)"
export PATH="$HOME:/.rbenv/versions/3.1.3/bin


text:
Q: UnicodeEncodeError when run SSD test code I'm trying ro run the tensorflow/ssd_tests code with spyder in win10 (python 3.5 tensorflow 1.1).
And I got an error like:
    File "D:\software\anaconda\envs\tensorflow\lib\site-packages\zmq\utils\jsonapi.py", line 43, in dumps
    s = s.encode('utf8')
    UnicodeEncodeError: 'utf-8' codec can't encode character '\udcd5' in position 2896: surrogates not allowed`

I run the code step by step, and I found when run the code provider = slim.dataset_data_provider.DatasetDataProvider() the error occus.
In the file dataset_data_provider which function DatasetDataProvider()in, codekey, data = parallel_reader.parallel_read()fromfrom tensorflow.contrib.slim.python.slim.data import parallel_reader` will course the error.
The function of parallel_read() is this:
    def parallel_read(data_sources,
              reader_class,
              num_epochs=None,
              num_readers=4,
              reader_kwargs=None,
              shuffle=True,
              dtypes=None,
              capacity=256,
              min_after_dequeue=128,
              seed=None,
              scope=None):
    data_files = get_data_files(data_sources)
    with ops.name_scope(scope, 'parallel_read'):
      filename_queue = tf_input.string_input_producer(
    data_files, num_epochs=num_epochs, shuffle=shuffle, seed=seed,
    name='filenames')
      dtypes = dtypes or [tf_dtypes.string, tf_dtypes.string]
      if shuffle:
        common_queue = data_flow_ops.RandomShuffleQueue(
      capacity=capacity,
      min_after_dequeue=min_after_dequeue,
      dtypes=dtypes,
      seed=seed,
      name='common_queue')
      else:
        common_queue = data_flow_ops.FIFOQueue(
      capacity=capacity, dtypes=dtypes, name='common_queue')
      summary.scalar('fraction_of_%d_full' % capacity,
               math_ops.to_float(common_queue.size()) * (1. / capacity))
      return ParallelReader(
    reader_class,
    common_queue,
    num_readers=num_readers,
    reader_kwargs=reader_kwargs).read(filename_queue)

Is dtype the cause of this error?
And how shoud I get rid of this?
Thank you!
I have found the reason. When the model was loaded correctly, the error disappeared.


text:
Q: Kivy development in eclipse PyDev on Ubuntu 14.04 SetUp I begun to develope with Python and Kivy and I really like it :-) For daily business I'm a Java developer and also a an eclipse child. So i decided to setup eclipse (Mars) with Python, means install PyDev-Plugin and create the settings (done in one button-click).
But I have a problem, my eclipse do not want to recognize the kv-files as python files.
So my question has anyone experience with this set up?
Do anyone knows a good set up tutorial?
Thanks for your help

A: *.kv files aren't Python files.  I don't think trying to treat them as such is really what you want to do.  If you must, you can choose to treat *.kv files as python files by going to Preferences > General > Editors > File Associations and adding an entry for *.kv with the Python Editor as an associated editor.
My own personal preference, however, is to use YEdit YAML editor for *.kv files.  It won't recognize Python syntax in expressions, but it works well enough for me.  If you're willing to use an external editor, you can get Kv-lang syntax highlighting in Vim.  If you're willing to learn to use Vim.  Which you should, because Vim is awesome.
Finally, if you're willing to pay, the developer of PyDev also develops a closed source fork of Eclipse called Liclipse, which, if I recall correctly, has syntax highlighting, outlining, and autocomplete in kv files.


text:
Q: Create New Table with Unpivot and Dynamic Columns I have been trying to unpivot a large database with dynamic columns while keeping two indexed columns. I can't get it to save as a new table in SQL Server Management Studio as a new table. Right now I'm getting 'An INSERT statement cannot contain a SELECT statement that assigns values to a variable.'
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

create table pivot_columns ([Prime Item Nbr] NVARCHAR(MAX), [Store Nbr] NVARCHAR(MAX))

insert into pivot_columns

select @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(column_name)
                      FROM information_schema.columns
                      WHERE table_name = 'POSSalesMicro'
                        AND COLUMN_NAME <> 'Prime Item Nbr'
                        AND COLUMN_NAME <> 'Store Nbr'
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)')
                        , 1, 1, '');

SELECT @query = 'WITH Unpivoted
                AS
                (
                    SELECT [Prime Item Nbr], [Store Nbr], columns, value
                    FROM POSSalesMicro
                    UNPIVOT
                    (
                       columns
                       FOR value IN('+ @cols + ')
                    ) AS u
                )
                SELECT
                  [Prime Item Nbr],
                  [Store Nbr],
                  columns,
                  CAST(CASE WHEN value LIKE ''% POS Sales'' THEN REPLACE(value,''POS Sales'', '''')
                       WHEN value LIKE ''LR%'' THEN REPLACE(value,''LR '', '''')
                  END AS INT) AS WMWeek
                FROM Unpivoted';

EXECUTE(@query);

A: You would need to make the insert part of your dynamic sql. Something along these lines.
select @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(column_name)
                      FROM information_schema.columns
                      WHERE table_name = 'POSSalesMicro'
                        AND COLUMN_NAME <> 'Prime Item Nbr'
                        AND COLUMN_NAME <> 'Store Nbr'
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)')
                        , 1, 1, '');

SELECT @query = 'WITH Unpivoted
                AS
                (
                    SELECT [Prime Item Nbr], [Store Nbr], columns, value
                    FROM POSSalesMicro
                    UNPIVOT
                    (
                       columns
                       FOR value IN('+ @cols + ')
                    ) AS u
                )
                insert into pivot_columns (' + @cols + ')
                SELECT
                  [Prime Item Nbr],
                  [Store Nbr],
                  columns,
                  CAST(CASE WHEN value LIKE ''% POS Sales'' THEN REPLACE(value,''POS Sales'', '''')
                       WHEN value LIKE ''LR%'' THEN REPLACE(value,''LR '', '''')
                  END AS INT) AS WMWeek
                FROM Unpivoted';

exec sp_executesql @query


text:
Q: Reading a file using fgetc is giving extra (garbage) values I have created a function to read data from a text file. The function reads data into a buffer and then copies it into a separate variable as the buffer gets filled.
I noticed that the line_size (see reference below) variable is overstepping the actual size of the line i.e the value of line_size is 106 while the actual length of my line is 103 characters.
So to debug, I added a print statement which corresponded each character read to the current buffer size: printf("%c\t%i\n",c,current_buffer_size);
Once I ran the program, turns out that fgetc is reading some 'garbage' characters (see screenshot below).
(reference: char *line stores data from the buffer, int line_size keeps track of the size of char *line )
Note: the value of FILE_BUFFER is 128

char *readline(FILE *fptr)
{
  char buffer[FILE_BUFFER];
  char *line = malloc(sizeof(char));
  int current_buffer_size, line_size = 0;
  int c;
  int is_reading = 1;

  while(is_reading)
  {
    current_buffer_size = 0;
    while(current_buffer_size < FILE_BUFFER)
    {
      c = fgetc(fptr);
      if ( c == '\n' || feof(fptr))
      {
        is_reading = 0;
        break;
      }
      buffer[current_buffer_size] = c;
      current_buffer_size += 1;
      printf("%c\t%i\n",c,current_buffer_size);
    }
    line_size += current_buffer_size;
    line = (char *) realloc(line,line_size*sizeof(char));
    memcpy(&line[line_size-current_buffer_size], buffer, current_buffer_size);
  }
  if (line_size == 0) return NULL;
  line = (char *) realloc(line,(line_size+1)*sizeof(char));
  line[line_size] = 0;
  printf("\n%i\n",line_size); // final size of the line
  return line;
}

What could be the reason for this?

A: Thank you all for your helpful comments. The issued has been resolved thanks to @JonathanLeffler and @dasblinkenlight
So the problem appeared to be that some characters in the file were falling out of the single byte UTF-8 range (0-127). Since my text editor and terminal are both running in this UTF-8 mode, these characters were not displayed. A binary dump of each character (using xxd -b -c2 file.txt) revealed this problem. (Full disclosure: the text file was exported from whatsapp).
Memory dump showing the out of range characters (left) and 'garbage values' (right)

(The three characters: 11100010 10000000 10001110 were causing trouble)
This would also explain the other seemingly inexplicable memory errors the application was throwing due to the 'extra counting' of characters. A lot makes sense now.


text:
Q: What points to be used for Drawing Hexagonal Shaped Button Using below code I am able to draw arrow shaped button(shown below) ,but I want to draw hexagone(shown below as result image) ,so that I can use png image of size 175x154 as button image ,What Points I need to use to draw this ? and i need to to draw 6 such buttons ,how do i achieve this ?

private void Parent_Load(object sender, EventArgs e)
{
    // Define the points in the polygonal path.
    Point[] pts = {
        new Point( 20,  60),
        new Point(140,  60),
        new Point(140,  20),
        new Point(220, 100),
        new Point(140, 180),
        new Point(140, 140),
        new Point( 20, 140)
    };

    // Make the GraphicsPath.
    GraphicsPath polygon_path = new GraphicsPath(FillMode.Winding);
    polygon_path.AddPolygon(pts);

    // Convert the GraphicsPath into a Region.
    Region polygon_region = new Region(polygon_path);

    // Constrain the button to the region.
    btnExam.Region = polygon_region;

    // Make the button big enough to hold the whole region.
    btnExam.SetBounds(
        btnExam.Location.X,
        btnExam.Location.Y,
        pts[3].X + 5, pts[4].Y + 5);
}

A: The input should be a Rectangle which contains the Hexagonal shape, from that input we will calculate the Points for your Hexagonal shape, something like this:
public Point[] GetPoints(Rectangle container){
  Point[] points = new Point[6];
  int half = container.Height / 2;
  int quart = container.Width/4;
  points[0] = new Point(container.Left + quart, container.Top);
  points[1] = new Point(container.Right - quart, container.Top);
  points[2] = new Point(container.Right, container.Top + half);
  points[3] = new Point(container.Right - quart, container.Bottom);
  points[4] = new Point(container.Left + quart, container.Bottom);
  points[5] = new Point(container.Left, container.Top + half);
  return points;
}
private void Parent_Load(object sender, EventArgs e) {
  //This should be placed first
  // Make the button big enough to hold the whole region.
  btnExam.SetBounds( btnExam.Location.X, btnExam.Location.Y, 100, 100);

  // Make the GraphicsPath.
  GraphicsPath polygon_path = new GraphicsPath(FillMode.Winding);
  polygon_path.AddPolygon(GetPoints(btnExam.ClientRectangle));

  // Convert the GraphicsPath into a Region.
  Region polygon_region = new Region(polygon_path);

  // Constrain the button to the region.
  btnExam.Region = polygon_region;
}

You should update the Region whenever your btnExam's Size changes, so you should define some method called UpdateRegion and call it in a SizeChanged event handler:
private void UpdateRegion(){
  GraphicsPath polygon_path = new GraphicsPath(FillMode.Winding);
  polygon_path.AddPolygon(GetPoints(btnExam.ClientRectangle));
  btnExam.Region = new Region(polygon_path);
}
//SizeChanged event handler for your btnExam
private void btnExam_SizeChanged(object sender, EventArgs e){
  UpdateRegion();
}
//Then you just need to change the size of your btnExam in Parent_Load
private void Parent_Load(object sender, EventArgs e) {
  //The button should be square
  btnExam.SetBounds( btnExam.Location.X, btnExam.Location.Y, 100, 100);
}

A: Is this what you mean?
var xDisp = 10;

var yDisp = 10;

var length = 10;

var ls32 = (int)(length * Math.Sqrt(3) / 2.0);

var half = (int)(length / 2.0);

var points = new[]
{
    new Point(xDisp + length,   yDisp),
    new Point(xDisp + half,     yDisp + ls32),
    new Point(xDisp - half,     yDisp + ls32),
    new Point(xDisp - length,   yDisp),
    new Point(xDisp - half,     yDisp - ls32),
    new Point(xDisp + half,     yDisp - ls32)
};


text:
Q: Laravel 5.3 withValidator() was executed before validation ends /**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'some_id' => ['required', 'exists:some_model,id'],
    ];
}

/**
 * Configure the validator instance.
 *
 * @param \Illuminate\Validation\Validator $validator
 * @return void
 */
public function withValidator(Validator $validator)
{
    $validator->after(function (Validator $validator) {
        if ($this->has('some_id') && Model::find($this->get('some_id'))->eloquent->isBlocked()) {
            throw CustomException();
        }
    });
}

*

*In Laravel docs it is written that withValidator() works after validation is completed. In my case I have a validation rule 'exists' but withValidator() is executed before that so 'exists' rule was ignored here and error is occurring.

*Any suggestion to fix the issue would be really really helpful. Thanks


text:
Q: How does HibernateTemplate and Spring @Transactional work together? We use HibernateTemplate in our DAOs for all the CRUD operations.
My question is, we use spring @Transactional on the services, Because the spring is managing the transactions, how does the HibernateTemplate behave in the senario where I update multiple DAOs. Meaning does HibernateTemplate use same session across  different DAOs when Spring @Transactional is used?
@Transactional
public boolean testService(SObject test)[

     dao1.save(test.getOne());
     dao2.save(test.gettwo());

}

This is how the DAO class looks:
public class GenericHibernateDao<T, PK extends Serializable> extends HibernateDaoSupport
.
.
.
public PK save(T newInstance) {
    return (PK) getHibernateTemplate().save(newInstance);
}

A: The HibernateTransactionManager javadoc is pretty clear about this:

This transaction manager is appropriate for applications that use a single Hibernate SessionFactory for transactional data access, but it also supports direct DataSource access within a transaction (i.e. plain JDBC code working with the same DataSource). This allows for mixing services which access Hibernate and services which use plain JDBC (without being aware of Hibernate)! Application code needs to stick to the same simple Connection lookup pattern as with org.springframework.jdbc.datasource.DataSourceTransactionManager (i.e. DataSourceUtils.getConnection or going through a TransactionAwareDataSourceProxy).

You're fine as long as you are accessing the connection through helper classes that are aware of the connection proxy such as DataSourceUtils (and the JdbcTemplate uses that behind the hood)


text:
Q: how to associate vibration with a button click Hi
    I my app there is a button with which i want to associate vibration.Can some one tell me the code to be put into the method associated with the button.Thanks.

A: try this:
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Don't forget to import AudioToolbox/AudioToolbox.h

A: We need to put the line
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
in a different method then call the method in the method corresponding to the button.


text:
Q: How to navigate user to specific page using window.onbeforeunload I want to navigate user to particular page using onbeforeunload. Is there a way to implement it?
window.onbeforeunload = function() {
          //return 'The changes you made will be lost if you navigate away from this page.';
          if (flag) {
              navigateTo('index');
              else {
                  navigateTo('list');
              }
          }
          return 'The changes you made will be lost if you navigate away from this page.';
      };


text:
Q: matlab on linux can't plot anything(can't load libstdc++.so.6: version `CXXABI_1.3.8' not found) I'm running matlab R2016a on Fedora 24 and I can't use the plot command.
This is the error I get:

Error using gca
While setting the 'Parent' property of 'Axes':
Can't load
  '/usr/local/MATLAB/R2016a/bin/glnxa64/libmwosgserver.so':
  /usr/local/MATLAB/R2016a/bin/glnxa64/../../sys/os/glnxa64/libstdc++.so.6:
  version 'CXXABI_1.3.8' not found (required by /lib64/libGLU.so.1)
Error in newplot (line 73)
ax = gca(fig);

Also I have seen
How to fix: [program name] /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found (required by [program name])
and it doesn't help.

A: I had the same problem with that version of matlab and fedora. It seems that matlab prepends its own library paths on startup to LD_LIBRARY_PATH.
You can start up matlab with and tell it to use the right version of libstdc++ using the following:
LD_PRELOAD=/usr/lib64/libstdc++.so.6 matlab -desktop
What I did was add an alias to my .bashrc file:
alias matlab='LD_PRELOAD=/usr/lib64/libstdc++.so.6 matlab -desktop'
Hope that helps!

A: What I did was I edited a file called .matlab7rc.sh (located in "path_to_ matlab/bin" folder and its hidden) and uncommented all lines that were(there are several of them):
LDPATH_PREFIX='$MATLAB/sys/opengl/lib/$ARCH'
The following is stated in the file for uncommenting this line(s)

To always use the OpenGL libraries shipped with MATLAB uncomment the next
  line.

Although it certainly did the trick I'm curious whether using OpenGL that was shipped with MATLAB degrades the performance and in general how does this approach compares to @joe_st_amand's answer.

A: Alternate fix:
Rename the libstdc++.so.6 library file so that MATLAB cannot find it and is forced to use the system's version of the library. This file is located in matlabroot/sys/os/glnxa64/
Source: https://in.mathworks.com/matlabcentral/answers/329796-issue-with-libstdc-so-6
I tried and it worked like charm.

A: The following worked in fedora 28 scientific
> cd ~/usr/lib64
> ls libstd*

For me the output was
libstdc++.so.6  libstdc++.so.6.0.25

So I just added an alias in ~/.bashrc with the directory to libstdc++.so.6.0.25
> emacs ~/.bashrc

Write following line at the end:
alias matlab='LD_PRELOAD=/usr/lib64/libstdc++.so.6.025  /your/dir/to/bin/glnxa64/MATLAB -desktop'

Where /your/dir/to/ is the directory of your MATLAB installation. Then
> source ~/.bashrc

and after that I just run > matlab in terminal and all is OK.
EDIT. Add it to a desktop entry
You must make/edit a matlab.desktop file with the following, and place it in your .applications folder in order to works.
[Desktop Entry]
Name=Matlab R2017a
Exec=LD_PRELOAD=/usr/lib64/libstdc++.so.6.0.25 /usr/local/MATLAB/R2017a/bin/matlab -desktop &
Icon=~/username/.icons/Matlab_Logo.png
Terminal=false
Type=Application
Categories=Development;Science;Education

When opening from the desktop entry, it will load the appropiate libstdc. Works well.


text:
Q: how to take the first letters in Mysql request I have an sql request, that contains 3 parameters:
Article   Name_customer  id_customer.

My request is:
select "Article", "Client", "Name", round(sum("Montant_fac_eur")) as turnover
from "foundry_sync"."data"
where "Nature"='Repair'

and "annee" = {{w_widget24.selectedValue}}

and extract(month from "Facturation") between 0+{{w_widget4.selectedValue}} and 2+{{w_widget4.selectedValue}}
--and "Facturation" = {{w_widget6.selectedValue}}
group by "Article", "Client", "Name"
order by turnover DESC limit 5

I used the id_customer in the axis of abscissa, but I want change it by the name.
The problem is the name of my customers are long.
Can I do a test on the name to take just the 5 first letters, to display it in my dashboard ?
PS.: Knowing that I have some names are similarly, looks like:
AEROSPARES 2000 LTD
AEROSPARES SHANNON

Thanks

A: You can use the LEFT function as follows to select the first 5 characters of id_customer
SELECT LEFT(`id_customer`, 5)...


text:
Q: WCF regarding class property types Ok so I am building my WCF service. I am having an issue with my proxy not generating code for classes that have types such as ListViewItem, or even the class objects that I already have defined.
Two examples below are classes that I am trying to pass.
Example #1
[DataContract]
public class InvoiceCharges {
    #region Property...
    private int _invoiceChargeID;
    private ListViewItem _listViewItem;

    [DataMember]
    public int InvoiceChargeID {
        get { return _invoiceChargeID; }
        set { _invoiceChargeID = value; }
    }
    [DataMember]
    public ListViewItem ListViewItem {
        get { return _listViewItem; }
        set { _listViewItem = value; }
    }
    #endregion

Example #2
[DataContract]
public class Users {
    #region Properties...
    private int _userID;
    private Divisions _Division = new Divisions();

    [DataMember]
    public int UserID {
        get { return _userID; }
        set { _userID = value; }
    }
    [DataMember]
    public Divisions Division {
        get { return _Division; }
        set { _Division = value; }
    }

In the 2nd example I am confused why it has a hard time just passing my Division class that it already sees. Surely WCF can pass your own custom objects?? Any help is greatly appreciated, I know on other platforms in order to Serialize your own custom object you have to do something special to your class. I wasn't sure if WCF handled this automatically or not.
EDIT
Any other help on this is still appreciated.
I have also tried adding the following to the InvoiceCharges class but was still unable to see the proxy generate correctly.
[KnownType(typeof(ListViewItem))]

Also, this is the behavior of the proxy. I am using Add Service Reference to do this.

See how it is generating several "InvoiceCharges" its all because of that ListViewItem. I can remove the DataMember attribute off of it and its fine.

A: A ListViewItem is a UI concept and serves no purpose in your business or service code. Rethink the "data" (models) and not what the user sees and retool the class.
Your problem deals with the inability to serialize. Unless you want to rewrite UI bits to make them more serialization friendly, rethinking the model is your best bet.


text:
Q: SQL + Ajax update limit for each day I created a sort of voting website with PHP and a MYSQL database. People can vote on id's that are in the database and the amount of likes goes up.
When you click on a button the likes of that specific id goes up by one. This is done through Ajax and sql.
Is it possible to set a limitation of the amount of likes an id can have for each day. For instance each id can update only 10 times each day. And the next day another 10 times.

A: Yes, you can put condition in ajax code.
Before inserting record in DB for vote first check the total number of vote received for that ID on current day.
If it is equal to 10 then skip the operation or else increase the vote.
You have to put this conditions in this file /10jaar/views/submissions.php
Not a big deal i think so.


text:
Q: permission denied when doing fopen on a 777 permission file in php Im not new to php or file permissions. But i just migrated an extremely simple script to a new server I setup.
The folder which the script runs is in the document root.
The permissions for the folder are set to 755.
The owner of the folder is gsta.
The owner of the file is gsta.
I turned on error_reporting and am getting:
Warning: fopen(log.txt): failed to open stream: Permission denied in /var/www/html/log.php on line 13

I've tried:
chmod("log.txt", 0777)

in php and also get permission denied.
Ive done:
ps -u | grep httpd

and got:
gsta      1012  0.0  0.0 108608   808 pts/3    S+   22:45   0:00 grep --color=auto httpd

Code:
$filename = 'log.txt';
$handle = fopen($filename,"a+");
echo "fh:" . fwrite($handle, $payload . "\n") . $handle . "<br/>";
fclose($handle);

even though it shouldnt matter PHP safemode is off
I tried setting the owner of the file to nobody (apache often runs under nobody, i also tried setting the owner to apache.
I have looked at every posting in google and its always the basic things, all of which I have tried. This was a known working script on a different server. I tried checking php.ini looking for some setting that would cause this issue.
I have tried deleting the file (as it should create it in that case)
Does anyone have any ideas? Ive tried everything I can think of.

A: Is there any possibility that some security stuff, like SELinux, stopped these actions?
I've run into a similar problem and the command setenforce 0, which would shut down SELinux, successfully resolved it.

A: httpd or apache user is different.
Check apache username from script with
<?php echo exec('whoami'); ?>

A: I don't know what it could be, but have your tried creating the file from within your script.
just rename the file, make sure fopen is set to read write mode (a should be fine) and have php create it for you.
If that doesn't work then your folder permissions are wrong, try setting the folder to 777
also on my box for some reason I have to use two zeros for chmod, 00777

A: "log.txt" are you sure the file you're setting to 777 is the same one? Without a path to it, if the page thinks its running from say the root directory of your site, not the one you're in, you could get errors that way, the Some calls tend to also need the directory to have write permission - I dont think I ever got to the bottom of why some do, some dont.


text:
Q: Reflected Brownian Motion Let $Y(t)$ be a reflected Brownian motion, and $G(t)$ is the process which keeps count of number of times that $Y(t)$ has hit the X axis. How do I approach to find distribution of $G(t)$, or almost sure growth rate bound on $G(t)$.

A: As your reflected Brownian motion is nothing else then the absolute value of a Brownian motion you have $$ \{t \in [0,T]  :  Y_t = 0\} = \{t \in [0,T]  :  \vert W_t \vert= 0\} = \{t \in [0,T]  :  W_t = 0\}$$ which is a Lebesgue null set (however, an uncountable one, as remarked in the comments). In point of view of distribution, $Y_t$ has the same law as the difference of the Maximum process of a Brownian motion and the Brownian itself, $\max_{0 \leq s \leq t} W_s - W_t$. For details see, e.g., Karatzas & Shreve, Brownian Motion and Stochastic Calculus, Chapter 3.6.C, p.210ff. More general, your problem is known as Skorohod problem (which should not be confused with the Skorohod embedding problem), and I believe there is a fair amount of queueing theoretic literature about.


text:
Q: default lightning:inputField dependent picklist In Visualforce/Standard Salesforce UI, if you have a required dependent picklist with only one value, it will default the field to that value and not allow the user to change the value.
Is there any way to replicate that functionality with lightning:input field? I know that we can get the picklist values in the apex controller but I'm hoping there's some way to get the filtered list based on the controlling field.

A: Refer to the sample code extract below from the documentation.
The lightning:inputField of the dependent required picklist field gets defaulted if a single value exist.
This example uses LeadSource as the controlling field and Level__c as the dependent field for a dependent picklist.
<lightning:recordEditForm aura:id="recordViewForm"
                                  recordId="{!v.recordId}"
                                  objectApiName="Contact">
    <lightning:messages />
    <!--Other fields here-->
    <lightning:inputField fieldName="LeadSource" />
    <lightning:inputField fieldName="Level__c" />
    <lightning:button aura:id="submit" type="submit" label="Update record" class="slds-m-top_medium"/>
</lightning:recordEditForm>

A: public without sharing class DemoClass {
private static final String base64Chars = '' +
            'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
            'abcdefghijklmnopqrstuvwxyz' +
            '0123456789+/';
    public class Bitset{
        public Map<String,Integer> AlphaNumCharCodes {get;set;}
        public Map<String, Integer> Base64CharCodes { get; set; }

        public Bitset(){
          loadCharCodes();
        }

        //Method loads the char codes
        @TestVisible
        public void loadCharCodes(){
            AlphaNumCharCodes = Constants.AlphaNumCharCodes;
            Base64CharCodes = new Map<String, Integer>();
            //lower case
            Set<String> pUpperCase = AlphaNumCharCodes.keySet();
            for(String pKey : pUpperCase) {
                //the difference between upper case and lower case is 32
                AlphaNumCharCodes.put(pKey.toLowerCase(),AlphaNumCharCodes.get(pKey)+32);
                //Base 64 alpha starts from 0 (The ascii charcodes started from 65)
                Base64CharCodes.put(pKey,AlphaNumCharCodes.get(pKey) - 65);
                Base64CharCodes.put(pKey.toLowerCase(),AlphaNumCharCodes.get(pKey) - (65) + 26);
            }

            //numerics
            for (Integer i=0; i<=9; i++){
                AlphaNumCharCodes.put(string.valueOf(i),i+48);
                //base 64 numeric starts from 52
                Base64CharCodes.put(string.valueOf(i), i + 52);
            }
        }
    }

    public class TPicklistEntry{
        public string active {get;set;}
        public string defaultValue {get;set;}
        public string label {get;set;}
        public string value {get;set;}
        public string validFor {get;set;}
        public TPicklistEntry(){

        }
        public TPicklistEntry(string label,string value){
            this.label=label;
            this.value=value;
        }
    }

    //----------------------------------------------------------------------------------------------------------
    //get dependent picklist values
    //
    //
    //----------------------------------------------------------------------------------------------------------
    public static Map<String,List<String>> getDependentOptions(String pObjName, String pControllingFieldName, String pDependentFieldName){

        Map<String,List<String>> objResults = new Map<String,List<String>>();
        //get the string to sobject global map
        Map<String,Schema.SObjectType> objGlobalMap = Schema.getGlobalDescribe();
        if (!objGlobalMap.containsKey(pObjName))
            return objResults;
        //get the type being dealt with
        Schema.SObjectType pType = objGlobalMap.get(pObjName);

        Map<String, Schema.SObjectField> objFieldMap = pType.getDescribe().fields.getMap();
        system.debug('objFieldMap' + objFieldMap);
        //verify field names
        if (!objFieldMap.containsKey(pControllingFieldName) || !objFieldMap.containsKey(pDependentFieldName))
            return objResults;
        //get the control values
        List<Schema.PicklistEntry> ctrl_ple = objFieldMap.get(pControllingFieldName).getDescribe().getPicklistValues();
        //get the dependent values
        List<Schema.PicklistEntry> dep_ple = objFieldMap.get(pDependentFieldName).getDescribe().getPicklistValues();
        //iterate through the values and get the ones valid for the controlling field name
        DemoClass.Bitset objBitSet = new DemoClass.Bitset();
        //set up the results
        for(Integer pControllingIndex=0; pControllingIndex<ctrl_ple.size(); pControllingIndex++){
            //get the pointer to the entry
            Schema.PicklistEntry ctrl_entry = ctrl_ple[pControllingIndex];
            //get the label
            String pControllingLabel = ctrl_entry.getLabel();
            //create the entry with the label

            objResults.put(pControllingLabel,new List<String>());
        }
        //Added Navin - For None value
        if(!objResults.containsKey('--None--')){
            objResults.put('--None--',new List<String>{'--None--'});
        }
        //End
        //check the dependent values
        for(Integer pDependentIndex=0; pDependentIndex<dep_ple.size(); pDependentIndex++){
            //get the pointer to the dependent index
            Schema.PicklistEntry dep_entry = dep_ple[pDependentIndex];
            //get the valid for
            String pEntryStructure = JSON.serialize(dep_entry);

            DemoClass.TPicklistEntry objDepPLE = (DemoClass.TPicklistEntry)JSON.deserialize(pEntryStructure, DemoClass.TPicklistEntry.class);
            //if valid for is empty, skip
            if (objDepPLE.validFor==null || objDepPLE.validFor==''){
                continue;
            }
            String validForBits = base64ToBits(objDepPLE.validFor);
            //iterate through the controlling values
            for (Integer i = 0; i < validForBits.length(); i++) {
                // For each bit, in order: if it's a 1, add this label to the dependent list for the corresponding controlling value
                String bit = validForBits.mid(i, 1);
                if (bit == '1') {
                       String pControllingLabel = ctrl_ple[i].getLabel();
                    objResults.get(pControllingLabel).add(objDepPLE.label);
                }
            }
        }
        if(objResults!=null){
            for(String pControllingLabel  :objResults.keyset()){
                //Added Navin - To remove duplicate None value
                if(pControllingLabel != '--None--'){ //End
                    objResults.get(pControllingLabel).add(new TPicklistEntry('--None--','--None--').label);
                }

            }
        }
        return objResults;
    }
    // Convert decimal to binary representation (alas, Apex has no native method :-(
    //    eg. 4 => '100', 19 => '10011', etc.
    // Method: Divide by 2 repeatedly until 0. At each step note the remainder (0 or 1).
    // These, in reverse order, are the binary.
    public static String decimalToBinary(Integer val) {
        String bits = '';
        while (val > 0) {
            Integer remainder = Math.mod(val, 2);
            val = Integer.valueOf(Math.floor(val / 2));
            bits = String.valueOf(remainder) + bits;
        }
        return bits;
    }

    // Convert a base64 token into a binary/bits representation
    // e.g. 'gAAA' => '100000000000000000000'
    public static String base64ToBits(String validFor) {
        if (String.isEmpty(validFor)) return '';

        String validForBits = '';

        for (Integer i = 0; i < validFor.length(); i++) {
            String thisChar = validFor.mid(i, 1);
            Integer val = base64Chars.indexOf(thisChar);
            String bits = decimalToBinary(val).leftPad(6, '0');
            validForBits += bits;
        }

        return validForBits;
    }
}

in this class Call the method getDependentOptions and pass the parameters.
to get the picklist values you can simply using Schema object.
You can use below code to get picklist values:
public static  Map sObjectFieldInfoMap;
    List pick_list_values = sObjectFieldInfoMap.get(field_name).getDescribe().getPickListValues();


text:
Q: Concurrent access of a resource object by different threads within a certain order Let's say I have a GameServer object which contains the data of a card game. 4 clients would access that object's functionality/data using Java RMI, and each of them are going to modify the game state in their own turn. After each player does a move, the others should be able to check the new state of the Game object. Being a card game, they also must follow a certain order of who should play at a certain time.
My first guess would be implement that using ReentrantLock + Condition, but I don't know how to manually assign which player should acquire the lock after the previous one release it.
Can somebody help me with that?

A: List of semaphores, one for each thread?
Each thread/player waits on its own semaphore in the list.  When it gets a unit, it 'plays', then signals the semaphore of the next thread/player along and loop around to wait on its own semaphore again.  If a player folds, or whatever, its thread can safely remove itself from the list before throwing the unit back into the semaphores.
At startup, throw in one unit to the first player to deal/whatever.
That solves mutual exclusion and play-order in one design.
It will work.
It's not messy.

A: On the server, you have some sort of game state that each player can modify only on her turn. Let's call this state variable gs; it doesn't matter what type it is.
The most practical way of handling the in-order behavior is for the gs class to have a field representing whose turn it is (int nextPlayer). Your server RMI method that accepts take-my-turn commands from the players will check the nextPlayer field and ensure that it's the sending player's turn and return an error if not (perhaps IllegalStateException). The RMI take-my-turn method and the reading methods should be synchronized(gs), since you need to make sure that the game state is updated atomically (including whose turn is next), and you won't be having much contention with four players.


text:
Q: Bash: truncate or crop part of binary file or stdin on CLI? If I have a binary file, or some command with a raw binary output, and I'm looking for a shell (bash) command to crop a specific part of data i.e. with given start and length or end offset in bytes.
For example, suppose file.bin contains abcdefghijk, I would do something like:
cat file.bin | crop 5 3
To indicate I want to keep only the portion from offset 5 with length 3, so this example would output fgh.
I know there is the cut command but it works on text content and processes the input line by line. In my case I'm typically dealing with binary data so there is no concept of lines. I simply want to specify the portion to be cropped in bytes.
Is there a binary alternative to cut?

A: dd will do that. If you need a granularity of one byte, you have to set the block size to 1:
cat file.bin | dd bs=1 skip=5 count=3

A: POSIX tail with -c can handle arbitrary data. Unfortunately POSIX head cannot. When limited to POSIX, you need dd; either like this:
<file.bin tail -c +6 | dd bs=1 count=3 2>/dev/null

Or like this:
<file.bin dd bs=1 skip=5 count=3 2>/dev/null

bs=1 may be sub-optimal, but even if your skip= and count= can be recalculated to a greater bs=, with POSIX dd only bs=1 is right for you.
GNU dd supports iflag=fullblock that may help in case of greater bs=. In your case with GNU dd a better option is iflag=skip_bytes,count_bytes:
<file.bin dd iflag=skip_bytes,count_bytes skip=5 count=3 2>/dev/null

The above command uses the default bs=512 and it works despite the fact neither 5 nor 3 are multiples of 512. The command should work with any sane bs=.
If your head supports -c to count bytes then it most likely does not wait for a full line when reading in this mode. This leads to the following method:
<file.bin tail -c +6 | head -c 3

There may be other solutions. Note if command1 prints the first 5 bytes from its input and command2 prints the first 3 bytes of its input then
{ command1 >/dev/null; command2; } <file.bin

may or may not work. In general command1 may read more than 5 bytes (and still print 5 to its stdout), so when command2 starts reading, the pointer may be in the wrong place. The commands I gave you do not follow this potentially flawed pattern.


text:
Q: Running Java Class under Linux terminal I'm trying to run a JAVA Class under Linux Mint from the Terminal.
My Java class runs nice within any IDE, so I know it's not a code problem, but actually need to run it from the Command Line this time. However, I'm having issues at this point.
I used the following command:
java -cp . Interface

But it happens that it gives me an java.lang.NoClassDefFoundError Exception:
Exception in thread "main" java.lang.NoClassDefFoundError: Interface (wrong name: client/Interface)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:788)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:447)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)

I'm looking to understand all the components that could make it possible to solve this issue and to be able to overcome future problems on the topic.
Thank you for your time.

A: Your class resides within the package client so you have to change the current directory to the parent directory and run it with java -cp . client.Interface. ls should show you a directory named client.
<current directory>
└ client
  └ Interface.class

So using the information you gave in the comments to another answer, your current directory should be NetBeansProjects/ServerClient/build/classes/ when starting the application using the above command line.

A: Provide package name as well:
java  -cp . client.Interface

Run this command from the Project root (aka at the same place where is your bin file)


text:
Q: TypeLoadException in .NET assembly with embedded Interop I developed a .NET class library with the following characteristics:

*

*.NET 4.0, Any CPU

*References adodb.dll from the .NET Primary Interop Assembly folder

*Builds with Embed Interop Type set to true (default)

*Exposes an ADODB.RecordSet for consumption by COM.

I expose the assembly to VBA via a VSTO AddIn. It runs fine on my machine, but on client machines my assembly throws a System.TypeLoadException when it tries to access the Fields property of a RecordSet.
public Recordset Test() {
    Recordset result = new Recordset();
    result.CursorLocation = CursorLocationEnum.adUseClient;
    Fields resultFields = result.Fields; // EXCEPTION THROWN HERE.
    ...
}

Exception message:
Could not load type 'ADODB.FieldsToInternalFieldsMarshaler' from assembly 'MyCompany.MyProduct.Interop.Com.
Failing clients: Win XP/32, Win 7/64.  Neither have local admin rights. Both have .NET 4.0

Update: This Post describes my problem. The accepted answer (late binding) did not work for me, but Bob's answer did (do not embed the Interop).
As soon as I set Embed Interop Types to False, everything started working as If by magic.
So my question has changed to "Why does embedding the interop not work?" I thought that was the best practice to avoid problems on client machines.


text:
Q: Internet Explorer ignores width of flexbox container The site I'm working has a responsive grid layout which I achieved with flexbox. The problem is, it looks really bad in IE (any version) because it for some reason it ignores the width of the containter and displays it much wider than the screen size.
I have managed to kinda fix this by adding a "max-width" but doesn't help much because the design is responsive.
This is what it's supposed to look like: http://gagadaily.com
This is what it looks like in IE: http://i62.tinypic.com/2v0dgf6.png
Here's the HTML. The content inside the container div is repeated many times.

Title

Description

Here's the css:
#ggd_forum_container {
display: -webkit-flex; /* Safari */
-webkit-flex-wrap: wrap; /* Safari 6.1+ */
display: -ms-flexbox;
display: flex;
flex-wrap: wrap;
position: relative;
width: 100%;
max-width: 945px;
}

.ggd_forum_box {
width: 31.8%;
margin: 0 0 1% 2.3%;
}

.ggd_forum_overlay {
height: 140px;
margin-bottom: 5px;
background-size: auto 150px;
background-position: center;
position:relative;
-webkit-box-shadow:inset 0px 0px 0px 1px rgba(0,0,0,0.1);
-moz-box-shadow:inset 0px 0px 0px 1px rgba(0,0,0,0.1);
box-shadow:inset 0px 0px 0px 1px rgba(0,0,0,0.1);
}

.ggd_forum_overlay:hover {
  box-shadow: 0 2px 4px rgba(0,0,0,0.5);
}

.ggd_forum_title {
box-sizing: border-box;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 22px;
font-weight: 400;
line-height: 1.2;
color: #FFF;
bottom:0;
left:0;
width: 100%;
padding: 10px;
position: absolute;
text-shadow: 1px 1px 0 rgba(0,0,0,0.5);
background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0,0,0,0)), to(rgba(0,0,0,0.5)));
background-image: -webkit-linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,0.5));
background-image: -moz-linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,0.5));
background-image: -o-linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,0.5));
background-image: -ms-linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,0.5));
background-image: linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,0.5));
}

Any help would be appreciated!

A: Flexbox is only fully supported since IE11, to use it with IE10 you must use the 2012 syntax. Before that, IE is not supported.
You should check here : http://caniuse.com/#search=flexbox


text:
Q: How to make toolbar icons work like a tab? I'm very new. Suppose I have a toolbar with 2 buttons: Foo and Bar. Is there a way to make each triggering a different "frame"? That is, the toolbar icons work like tabs. Should each trigger a new window by an on-click event?
Thanks

A: You can use QStackedWidget. It provides a way to have multiple widgets on each other where only one is displayed at a time (Like a QTabWidget). Here is an example :
self.stackedWidget = QtWidgets.QStackedWidget(self)
self.stackedWidget.addWidget(firstPageWidget)
self.stackedWidget.addWidget(secondPageWidget)

self.ayout = QtWidgets.QVBoxLayout(self)
layout.addWidget(stackedWidget)
setLayout(layout)

Now on each button click you can change the current page using setCurrentIndex.