text:
Q: Regular Function Constant on Projective Plane Minus a Point For context I'm trying to follow a proof that is linked in the answer to this question, but I'm stuck on one particular point.

Let $k$ be an algebraically closed field, and let $A$ and $B$ be distinct projective planes in $\mathbb{P}_k^3$ intersecting only at a line $L$, and let $X=A\cup B$. Let $D$ be a line on $A$ distinct from $L$, intersecting $L$ only at the point $P$.
Set $U=X\setminus D$. Then any $f\in\Gamma(U)$ is constant on $B\setminus D=B\setminus\{P\}$.

I'm not sure why this should be the case.
I know that a regular function on the projective plane must be constant, and I know that the ring of regular functions of an affine plane with a point removed is isomorphic to the of regular functions on the plane itself.
I thought then that perhaps the same is true for the projective plane. If we say $P=(0:0:1)$, then $B\setminus D=D^+(x)\cup D^+(y)$. Then any regular function on $B\setminus D$ can be written as $\frac{f(x,y,z)}{x^n}$ on $D^+(x)$ and $\frac{g(x,y,z)}{y^m}$ on $D^+(y)$. These must agree on $D^+(x)\cap D^+(y)=D^+(xy)$, but I can't see how to get a contradiction from here.
If non-constant regular functions do exist on $B\setminus D$ then we must somehow use the fact that $f$ is regular on all of $U$, but I can't see how.
Perhaps I've misread the argument in the proof, but everything else follows if I can show this, and I feel like I'm missing something obvious.
Any help would be much appreciated.

A: You can use the extension theorem for normal varieties to reduce to the projective case.
Here is the statement from Liu's book (Theorem 1.14 Chapter 4), though there should be a version of it in most books of AG (like Shafarevich or Hartshorne).

Theorem: Let $X$ be a normal locally noetherian scheme. Let $F$ be a closed subset of $X$ of codimension at least 2. Then the restriction
  $$ \mathcal{O}_X(X)\rightarrow\mathcal{O}_X(X\setminus F)$$
  is an isomorphism.


text:
Q: Using SystemParametersInfo from C# (SPI_GETSCREENREADER SPI_SETSCREENREADER) Am I doing this correctly?
[DllImport("user32", CharSet = CharSet.Auto)]
internal static extern long SystemParametersInfo(long uAction, int lpvParam, ref bool uParam, int fuWinIni);

...

public static bool IsScreenReaderRunning()
{
    long SPI_GETSCREENREADER = 70L;
    bool bScreenReader = false;
    long retVal;

    retVal = SystemParametersInfo(SPI_GETSCREENREADER, 0, ref bScreenReader, 0);

    //uint iParam = 0;
    //uint iUpdate = 0;
    //bool result = false;
    //bool bReturn = SystemParametersInfo(SPI_GETSCREENREADER, iParam, &bScreenReader, iUpdate);
    return bScreenReader;
}

public static void ScreenReaderOn()
{
    long SPI_GETSCREENREADER = 71L;
    bool bScreenReader = true;
    long retVal;

    retVal = SystemParametersInfo(SPI_GETSCREENREADER, 0, ref bScreenReader, 0);
}

public static void ScreenReaderOff()
{
    long SPI_GETSCREENREADER = 71L;
    bool bScreenReader = false;
    long retVal;

    retVal = SystemParametersInfo(SPI_GETSCREENREADER, 0, ref bScreenReader, 0);
}

A: The pinvoke declaration is completely wrong, it was copied from VB6 code.  The return type and arguments are not long (the VB6 int32 type), they are int.  Pinvoke.net is a decent site to get good declarations.
[DllImport("user32.dll", SetLastError = true)]
static extern bool SystemParametersInfo(int uiAction, int uiParam, IntPtr pvParam, int fWinIni);

Don't forget to throw Win32Exception when you get a false return so failure isn't silent.

A: Based on this article, the last parameter to SystemParametersInfo should be:
int SPIF_SENDCHANGE = 0x02;

When changing the value.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Avoid notification popup peek when app is in foreground From https://material.io/guidelines/patterns/notifications.html#notifications-behavior , I really we are able to notify user, without showing a notification peek.
I would like to show a flashing liked icon, in status bar, without pop up notification peek. (If you watch the first video under section From https://material.io/guidelines/patterns/notifications.html#notifications-behavior , you can see the flashing in status bar)
Flashing icon in status bar

However, I'm not entirely sure how to achieve that. Whenever I notify user, there will be a notification popup peek.
Notification popup peek

My code is as follow
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext(), org.yccheok.notification.Utils.createNotificationChannel())
    .setContentIntent(pendingIntent)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle(contentTitle)
    .setTicker(ticker)
    .setColorized(true)
    .setColor(context.getResources().getColor(R.color.accent_material_light))
    .setContentText(contentText);

mBuilder.setSound(Uri.parse(getStockAlertSound()));

mBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

mBuilder.setAutoCancel(true);

// Need BIG view?
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
// Sets a title for the Inbox style big view
inboxStyle.setBigContentTitle(contentTitle);
inboxStyle.setSummaryText(summaryText);
for (SpannableString notificationMessage : notificationMessages) {
    inboxStyle.addLine(notificationMessage);
}
mBuilder.setStyle(inboxStyle);

mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

I was wondering, when my app is in foreground, how can I avoid notification popup peek, but only show a flashing icon in status bar.

A: .setPriority(NotificationManager.IMPORTANCE_LOW)


text:
Q: Mearge two svg exports Fabric js Hi I have two canvas on one page and I want to export them in one svg file:
  var canvas = new fabric.Canvas('canvas');
  var canvas2 = new fabric.Canvas('c');
  var ctx = canvas2.getContext('2d');

Is there any chance to merge them or to merge svg export how looks like his:
canvas.toSVG();
canvas2.toSVG();


text:
Q: Is there a nice characterisation of topoi with nice meta-logical properties? First-order order classical logic with standard semantics has a proof theory: it is complete, sound and effective.
In higher order logic with standard semantics  one cannot obtain a proof theory - it cannot be simulateously complete, sound and effective.
Now, the internal language of a topos is higher order typed intuitionistic logic. Presumably like higher order classical logic it won't have nice meta-logical properties either.
Is there a nice characterisation for toposes with these nice properties for its internal language?

A: The undesirable properties of higher-order logic are created by an insufficient notion of model. That is, we cannot have all three, soundness, completeness and effectivness (decidability of proof checking), if we insist that formulas be interpreted in the "standard" set-theoretic way. Henkin semantics does not suffer from this defficiency.
What this says is not that something is wrong with higher-order logic, but that something is wrong with those who refuse to look at semantic models, even when they are right in front of their faces, because these models are "unintended", "philosophically unacceptable", "not what mathematicians think", etc. This phenomenon of refusing to accept new interpretations of old theories is quite persistent, and always very harmful. Didn't someone stall progress in noneuclidean geometry because it was unthinkable that there would be strange new models? Aren't imaginary numbers so called because they were unthinkable and did not "really exist"? Doesn't higher-order classical logic suffer because it is being denied its natural notion of models on the grounds that they are non-standard?
The natural notion of model for intuitionistic higher-order logic (IHOL) is that of a topos. With respect to topos semantics, it is a standard result that IHOL enjoys soundness, completeness and effectivness.
We may specialize this standard fact to classical higher-order logic (CHOL). The result then is that, with respect to Boolean topos semantics, CHOL enjoys soundness, completeness and effectivness. From here on, we may prove various technical theorems which allow us to cut down on the class of Boolean toposes which is stil sufficient for completeness. And then it is not much of a surprise that we cannot cut down just to a single topos known as classical sets, which is called "Paradise" by its prisioners.


text:
Q: parse live query cocoapods and Swift 3 I had a working project on Xcode 8.2.1 and swift 3. I wanted to add parse live query so I used cocoa pods to add the frame work. When I opened the workspace it said the syntax needed to be updated. Now I have over 500 errors in my app. Any ideas why this might have happened or how can I install the pod without this. Please ask for further info I'm not sure what would be useful here.
Thanks!

A: This is probably because the ParseLiveQuery version is out of date.
Try:
1) make sure your Podfile has pod 'ParseLiveQuery', '2.0.0' (latest version as of Apr. 2017)
2) run pod repo update then pod install
3) clean and rebuild your swift project


text:
Q: Let me link "best-of" answers to my resume profile Careers.Stackoverflow.com has one benefit for me. If an employer happens to find my resume, they can then browse through my SO answers to see how I work and how I think. I work very hard on my Stack Overflow answers and I would like employers to see what I can do.
But there are so many posts.
It would be nice if I could go through and highlight my best posts specifically to be linked with my resume profile (sort of a best-of). This link would be available for employers to peruse my most relevant posts without having to wade through a bunch of irrelevant fluff. It might also show tags I've participated in, average number of up-votes, and other information that might make me look good.
This would be a huge benefit to me and worth the price of admission many times over.

A: There are also answers that I put a lot of effort into, and for one reason or another they weren't voted very high or accepted.
But they're still answers that I'd be proud to show an employer because it shows a breadth that isn't highlighted by many other posts. (for example, I answered a linguistics question. It only got 4 upvotes, and it is the only linguistics question I've answered, but I'd really like to showcase the fact that I "Was able to apply my knowledge of linguistics to solve this problem")
So yeah, the same way one might highlight specific articles one wrote for a magazine or specific websites/projects, it seems like a good idea to, since SO careers is intended to be intertwined with our SO answers, be able to highlight things that we feel are particularly relevant to an employer or our abilities.

A: Seconded. I've answered a lot of questions, but my highest-rated answers tend to be the highly-viewed social-poll style questions, whereas most of the lowest tend to be simple RTFM-style answers; the interesting ones from an employer's POV - the sort where I give complex in-depth answers involving specialist knowledge - tend to get orders of magnitude fewer views that the social-poll questions, and hence fewer upvotes; and thus are buried somewhere in the middle of the "noise"; yet if I stop answering newbie questions, SO would lose something I think.
Perhaps if having me select questions to be highlighted is not acceptable, something like displaying the highest-rated question for each of the top few tags I am most active in might work.

A: You could also just delete the irrelevant fluff.
Or make up a list and paste the links into the "Projects and links" field.
Would be nice if that field allowed some sort of formatting though. Raw URLs with the ends cut off don't look all that great.
If it turns out a significant number of employers actually bother looking at this stuff, then i'd imagine they'd try to emphasize it more in the future.


text:
Q: sniff serial port - .net I have this Arduino code just for testing purpose:
int num=0;
void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.println(num);
    num+=1;
    delay(800);
}

Now it prints an integer and increments its value by one. When I open up Serial Monitor it prints as expected every 800ms.
My Arduino is connected on PORT-6
Now if I try to access the port, it says it is in use, I'm trying to access that from a .NET application. How can I do so?
c# code, collected from the internet, modified a little:
using System;
using System.IO.Ports;
using System.Threading;
namespace ConsoleApp1
{
    class Program
    {
        static SerialPort _serialPort;
        public static void Main()
        {
            _serialPort = new SerialPort();
            _serialPort.PortName = "COM6";//Set your board COM
            _serialPort.BaudRate = 9600;
            _serialPort.Open();
            while (true)
            {
                string a = _serialPort.ReadExisting();
                Console.WriteLine(a);
            }
        }
    }
}

How can I sniff data from that serial port ? [Educational Purpose]

A: You can't open a serial port twice.
If what you want is to get to see what is going through the bus (sniffing), you can use virtual ports and port forwarding, see here for a complete example.
Nothing will stop you from replacing any of the tools discussed in the link with your own code (.NET or other), in case they don't suit your needs or if you have enough determination to reinvent the wheel.


text:
Q: unable to detect Internet in android I have a fragment that has a WebView, everything works fine but I need to add a feature where if there is no Internet the fragment should display an error message with a try again button, for some reason my try again button is not working.
here's my code:
NewsFragment.java
public final class NewsFragment extends Fragment {

    private WebView mWebView;
    private ImageView img;
    private Button btnTryAgain;
    private LinearLayout mLinearLayout;
    private ConnectivityManager conMgr;
    private NetworkInfo networkInfo;
    .
    .
    .

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_news,container,false);
    }

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ((AppCompatActivity) getActivity()).getSupportActionBar().hide();

        //Initialization of the above declared variables
        mWebView = getView().findViewById(R.id.webView);
        img = getView().findViewById(R.id.img404);
        btnTryAgain = getView().findViewById(R.id.btnTryAgain);
        mLinearLayout = getView().findViewById(R.id.linearLayout404);

        //Checking if user is connected to the internet or not.
        conMgr = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        networkInfo = conMgr.getActiveNetworkInfo();

        //this is will work everytime the fragment is called or in onResume()
        //if INTERNET connected
        if (isConnected()) {
            mWebView.setWebViewClient(new WebViewClient());
            mWebView.loadUrl("https://news.google.com/");
        } else { //if INTERNET not connected
            mLinearLayout.setVisibility(View.VISIBLE);
            mWebView.setVisibility(View.GONE);
        }

        //TryAgain Button Event handling
        btnTryAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isConnected()) {
                    mLinearLayout.setVisibility(View.GONE);
                    mWebView.setVisibility(View.VISIBLE);
                    mWebView.setWebViewClient(new WebViewClient());
                    mWebView.loadUrl("https://news.google.com/");
                    Toast.makeText(getContext(), "Connected!", Toast.LENGTH_SHORT).show();
                } else { //if INTERNET not connected
                    Toast.makeText(getContext(), "No Internet :(", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    }
    public boolean isConnected(){
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }
}

Please help me I'm new to android

A: Use this permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

And use this Method:
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
        connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
    return true;
} else {
    return false;
}


text:
Q: How do i run a code every day at a set time? Swift I looked around but couldn't find any answers.
Anyone know how to run a block of code every day at 12:00 without using NSTimer?

A: You could setup a dispatch source to do this. Get the time remaining until noon as the start time and set the interval to every 24 hours. Something like:
let startTime = NSCalendar.currentCalendar().nextDateAfterDate(NSDate(), matchingHour: 12, minute: 0, second: 0, options: .MatchNextTime) ?? NSDate()
let startDelta = startTime.timeIntervalSinceNow * NSTimeInterval(NSEC_PER_SEC)
let periodicSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue())

dispatch_source_set_timer(periodicSource, dispatch_walltime(nil, Int64(startDelta)), 60 * 60 * 24 * NSEC_PER_SEC, NSEC_PER_SEC)
dispatch_source_set_event_handler(periodicSource) {
    print("bing bong!")
}
dispatch_resume(periodicSource)


text:
Q: Anonymous access to aspx for some users I have an asp website.I have a page which is visible to logged in users only.My problem is i need to show this page to some one else with out logging in.Want to make it anonymous.How can i achieve this?

A: Create a guest account & log the anonymous user automatically to that guest account when he visits particular page.

A: You can use this code in you web.config file to show some file without loging.
<location path="yourpage.aspx">
   <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>

It will allow for anonymous access.
Some links

*

*Allow anonymous authentication for a single folder in web.config?


text:
Q: Memory efficient lexical analysis with iterators I've been trying to design a lexer (for a programming language) that doesn't accumulate tokens in an intermediate list. This should be simple enough, and in C++ I figured this was a good use of iterators (I'm no expert at C++ by the way). That being said, I can't quite seem to find a satisfactory solution to the problem. This is the most logical thing I could come up with in the context of iterators:
enum class symbol {
  IDENTIFIER,
  ...
};
struct token {
  symbol symbol;
  std::string::const_iterator lexeme_begin;
  std::string::const_iterator lexeme_end;
};
class lexer {
private:
  std::string::const_iterator begin_, end_;
public:
  lexer(
      std::string::const_iterator begin,
      std::string::const_iterator end) :
      begin_ {begin}, end_ {end} {};
  class iterator;
  iterator begin() {
    return {begin_, end_};
  }
  iterator end() {
    // Can't figure out what to do here.
  }
};
class lexer::iterator {
private:
  std::string::const_iterator begin_, end_, next_;
public:
  iterator(
      std::string::const_iterator begin,
      std::string::const_iterator end) :
      begin_ {begin}, end_ {end} {};
  iterator operator++() {
    if (_next == _end) {
      // Same problem as in lexer::end.
    }
    _begin = _next;
    return *this;
  }
  token operator*() {
    // Perform actual lexical analysis here.
  }
};

I'd like to be able to do something like:
for (auto token : lexer {"abc 123"}) {
  std::cout << token;
}

My question is: Is this an appropriate use of iterators, and if so, how would I handle the lexer::end() iterator. The only way I could think to implement lexer::end() is by returning a special instance of lexer::iterator, but that doesn't seem like a good solution to me. The other thing that bothers me a little bit is that each iterator has to contain the same iterator to the end of the string, though this seems much less of a problem.

A: Yes, it looks like a reasonable place to use iterators. I haven't seen a lexer built quite like this, but it looks plausible.
To me, there is no objection to having a distinguished instance of lexer as the value of end(). It's often convenient for a lexer to return an EOF token that isn't really in the source code, and that's in effect the value of end(). Could well be a static.
I don't really understand why you need a class and a nested class to express the basic tokenisation logic. What you've shown us here is missing all the interesting stuff about actually delivering tokens, and seems overkill for a simple tokeniser and iterator support.
I'm guessing that your begin/end/next iterators serve the purpose of pointers into a stream of characters, so I don't understand each iterator has to contain the same iterator to the end of the string.

A: I ended up not implementing my lexical analyzer with a custom interface instead of an iterator. My confusion was that I was using a C++ iterators as if it were a generator http://en.wikipedia.org/wiki/Generator_(computer_programming). For simple input parsing, the standard library provides input streams (http://en.cppreference.com/w/cpp/io), but for more robust parsing I would recommend using a parsing library such as boost's spirit or simply writing your own custom interface.


text:
Q: Transformando clicks em função JS Estou tentando transformar meus clicks em funções, visto que o código está se repetindo em
https://github.com/rg3915/fs2w/blob/gh-pages/js/main.js
Esse é o código original:
$("#div1").click(function() {
  $("#widget-body1").slideToggle("slow");
});

$("#toggle1").click(function() {
  $("#widget-body1").slideToggle("slow");

  $('#toggle1').toggleClass(function() {
    if ($(this).is('.fa fa-chevron-down')) {
      return '.fa fa-chevron-up';
    } else {
      return '.fa fa-chevron-down';
    }
  })
});

Esse é o código que eu queria fazer:
function myfunc(par1) {
  $(par1).slideToggle("slow");
};

$("#div1").click(myfunc("#widget-body1"));

A: Se compreendi bem queres aplicar a ideia DRY nesse código para evitar repetição.
Uma coisa útil, caso estejas a usar IDs diferentes e com um numero a distinguir cada elemento é usar o ^= do jQuery. Assim os auscultadores de eventos ficam genéricos.
Sugestão:

function toggle(e) {
  var id = e.currentTarget.id;
  var nr = id.match(/\d+$/)[0]; // aqui extrais o numero do ID
  $('#widget-body' + nr).slideToggle('slow');
}

$('[id^=div]').click(toggle);
$('[id^=toggle]').click(function(e) {
  toggle(e);
  $(this).toggleClass('fa-chevron-up fa-chevron-down');
});
div.fa-chevron-up {
  display: none;
  padding: 10px;
  margin: 10px;
}

  <button type="button" id="div1">Toggle</button>

    Olá!
    <button type="button" id="toggle1">Fechar</button>

  <button type="button" id="div2">Toggle</button>

    Olá!
    <button type="button" id="toggle2">Fechar</button>

  <button type="button" id="div3">Toggle</button>

    Olá!
    <button type="button" id="toggle3">Fechar</button>


text:
Q: Toshiba C55t-A5123 Has no access to UEFI/CSM I have a Toshiba C55t-A5123 that had a Windows 10 upgrade installed on to a wiped hard drive. (No going to Settings to revert back to previous OS.)
The CD/DVD drive,(I had changed boot order to look at the Optical drive first), with a Win7 install disk was not recognized at boot up to facilitate a complete new Win7 install over top of the current Win10 OS.
I re-wiped the hard drive and formatted it to NTFS, and then used the disk manager from another laptop to change it to GPT!
When I tried to use my Windows 7 Ultimate DVD to re-install (changed boot order so OD CD\DVD was first) but this C55t wont boot from the DVD! Now this is the same DVD that came with this unit but yet it wont boot the Win7 install DVD!!
I read where THIS Toshiba model (because Toshiba was in cahoots with Microsoft) has no provision in BIOS to switch to from UEFI to CSM, UNLESS the bios was updated to v 1.03 (I think that is the latest version)! I did disable "Secure boot" which was the only associated option!
I then created a GPT UEFI USB memstick with Win7 Ult ISO, which booted fine and installed Win7 Ultimate to the re-GPT'ed 500gb SATA hard drive.
But on reboot after Win7 Ult install the ONLY bootable media device found was the USB Win7 memstick???
This C55t-A5123 will only boot to the memstick and completely bypasses (changed boot order to make HDD first) the GPT HDD that has just had Win7 Ulitmate successfully installed!
If I let it boot to the USB MEM stick it starts the Win& installation all over again!
If I remove the USB MEM stick,  I get "Checking Media" and then "No bootable Device -- please restart system" !
It completely ignores the Win7 install on the 500gb GPT SATA hard drive!
Apparently I still need to update BIOS so I can change UEFI to CSM. But how do I do that when there is no bootable device that contains the "scjev130.exe" executable file?
Is there a way to load/install this BIOS upgrade from a USB memstick?
I find it really reprehensible that such an option was deleted from BIOS choices,  just to make it difficult for a Toshiba user top revert back to windows 7!   That is what I have read anyway!
Thanks in advance for ANY input on how to get this Toshiba to recognize the install and/or how to upgrade the bios from memstick.


text:
Q: MongoDB with Python on Google Colab - syntax error on $elemMatch I have installed MongoDB inside the Google Colab VM, created a database, loaded a table and running quite a few commands successfully.
When I try to run the following command
db.restaurants.find({grades : { $elemMatch:{"score":{$gt : 90}}}})

i get the following error:
File "<ipython-input-28-86e6fcc5b428>", line 1
    db.restaurants.find({grades : { $elemMatch:{"score":{$gt : 90}}}})
                                    ^
SyntaxError: invalid syntax

I have looked at the documentation but I cannot find what is wrong. In fact, I copied a similar command from the documentation itself
db.survey.find(
   { results: { $elemMatch: { product: "xyz" } } }
)

and I got the exact same error!!
File "<ipython-input-33-8cd8460d9613>", line 2
    { results: { $elemMatch: { product: "xyz" } } }
                 ^
SyntaxError: invalid syntax

Now I am thoroughly puzzled. While doing the cut-and-paste, I have taken the trouble to paste in notepad to remove the possibility of hidden, non-printing characters.
What could be the issue here? Please help with any suggestions.
EDITS :
I am using python and pymongo package and my colab notebook is available here.

A: You need to put the JSON keys in quotes for python objects.
db.restaurants.find({"grades" : { "$elemMatch":{"score":{"$gt" : 90}}}})


text:
Q: Run rails code online Can any body give me a link to run rails code online??
I have tried codepad.org and tryruby.org they are running the ruby code fine
When I use Time.now it gives me correct result but when I try to run like below it give me errors:
time_ago_in_words(Time.now - 15.hours)
Thanks

A: The hours function is specific to Rails, which is a Ruby library. Rails is not loaded in CodePad. You'll have to install Rails on your computer to access those functions. Consult a guide for instructions. 1

A: Rails for Zombies provides an interpreter, but it's geared toward their lessons.


text:
Q: Compile error "no type named std::u16string" when compiling c++(clang) project for iOS with Qt dependencies and using c++11 I am trying to build a c++ library depending on Qt using clang for iOS.
My compile command is this:
xcrun --sdk iphoneos8.4 clang++ -Iinclude -I/Users/ls/projects/prompt-filesystem/src/../cpp_http -I/Users/ls/Qt/5.5/ios/include/QtNetwork -I/Users/ls/Qt/5.5/ios/include/QtCore -I/Users/ls/Qt/5.5/ios/include -std=c++11 -I/Users/ls/projects/haxe_libsodium/src/../dependencies/libsodium-ios/include -c -stdlib=libstdc++ -O2 -arch armv6 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.4.sdk -miphoneos-version-min=5.0 -Wno-parentheses -Wno-null-dereference -Wno-unused-value -Wno-bool-conversion -fno-stack-protector -DIPHONE=IPHONE -DIPHONEOS=IPHONEOS -DSTATIC_LINK -DHXCPP_VISIT_ALLOCS -DHXCPP_API_LEVEL=321 -I/usr/lib/haxe/lib/hxcpp/git/include -fexceptions -fstrict-aliasing -x c++ -Wno-invalid-offsetof /Users/ls/projects/prompt-filesystem/src/../cpp_http/QtHttp.cpp -oobj/iphoneos/e40135f5_QtHttp.o

The DHX... defines are because this is a hxcpp project. Now I am getting this build error:
In file included from /Users/ls/Qt/5.5/ios/include/QtNetwork/QNetworkAccessManager:1:
In file included from /Users/ls/Qt/5.5/ios/include/QtNetwork/qnetworkaccessmanager.h:37:
In file included from /Users/ls/Qt/5.5/ios/include/QtCore/QObject:1:
In file included from /Users/ls/Qt/5.5/ios/include/QtCore/qobject.h:41:
/Users/ls/Qt/5.5/ios/include/QtCore/qstring.h:739:55: error: no type named 'u16string' in namespace 'std'
static inline QString fromStdU16String(const std::u16string &s);

It is related to the fact that I am using c++11, but I want to do that because I need it at some other place.
The only suggestion I found was, that I should include "string" before including Qt. But I am doing that and it does not help.

A: Your command-line option -stdlib=libstdc++ is using gcc-4.2's standard library.  This is an ancient std::lib produced long before C++11.  std::u16string is new with C++11.
Instead of -stdlib=libstdc++, try -stdlib=libc++.


text:
Q: Cant show own element in Form I want to creat my own box in my Form. I do this code. But the ComboBox no appears (((
public class GUI {
    String RetVal1;
    String[][] RetValArr;
    private JFrame frame;
    private JLabel lblNewLabel;
    private JTextField Name_textField;

    private JFormattedTextField Phone_formattedTextField;

    static Connection conn3 = null;
    static int EC1;
    static int CurrentEntry;
    static String CurrentEntrySTR;

    private JTextField CurrentEnty_textField;
    private JTable table;

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUI window = new GUI();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }
    public GUI() {
        initialize();
    }

    private void initialize() {

        frame = new JFrame();
        frame.setBounds(100, 100, 504, 513);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JComboBox From_comboBox = new JComboBox();
        From_comboBox.setModel(new DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
        From_comboBox.setEditable(true);
        From_comboBox.setMaximumRowCount(2);
        From_comboBox.setBounds(274, 194, 186, 23);
        frame.getContentPane().add(From_comboBox);
        new ComboBoxDemo(frame);

        JComboBox Status_comboBox = new JComboBox();
        Status_comboBox.setBounds(274, 281, 186, 23);
        frame.getContentPane().add(Status_comboBox);

        CurrentEnty_textField = new JTextField();
    }
}

This is code for my own ComboBox ((
public class ComboBoxDemo {

    private List<Country> countries;
    private JComboBox cBox;

    public ComboBoxDemo(JFrame frame) {
        countries = createCountryList();
        cBox = createComboBox(countries);
        frame.add(cBox);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private JComboBox createComboBox(List<Country> countries) {
        final JComboBox comboBox = new JComboBox(countries.toArray());
        comboBox.setRenderer(new ComboBoxRenderer());
        comboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    Country country = (Country) comboBox.getSelectedItem();
                    System.out.println(country.getIso());
                }
            }
        });
        return comboBox;
    }

    private class ComboBoxRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            Country country = (Country) value;
            label.setText(country.getName());
            return label;
        }
    }

    private List<Country> createCountryList() {
        List<Country> list = new ArrayList<>();
        list.add(new Country("Afghanistan", "AF"));
        list.add(new Country("Åland Islands", "AX"));
        list.add(new Country("Albania", "AL"));
        return list;
    }

    public class Country {
        private String name;
        private String iso;

        public Country(String name, String iso) {
            this.name = name;
            this.iso = iso;
        }

        public String getName() {
            return name;
        }

        public String getIso() {
            return iso;
        }
    }

}

But i can't show my ComboBox in my GUI Form. I need to call it from my form but, when i Run the program - there are no errors, but no combobox in Form to...

A: At first using null layout is not a good idea. I think you should re-design your application. Check this discussion: why-is-it-frowned-upon-to-use-a-null-layout-in-swing
Your combobox is not shown, because in null layout all components needs to set size. You just forgot the use setBounds() for cBox.


text:
Q: Google Places API does not returns photos via photoreference in android I am using Google places API to get the details of particular restaurant.
Now, I wish to display the image of the restaurant in my android app .
For that, I referred this .
However, the  below link which is required to get an error gives me a 500 error and when I use http:// in the link instead of https:// , it gives an image which says you have exceeded the API limit.
I am using Glenter link description hereide to display these images. I dont think there's any issue with the Glide . The url generated does not gives any output.
Below is the code :
    String url = mPlaces.getIcon();
    String photoreference = mPlaces.getPhotoreference();
    String restaurantpic = "http://maps.googleapis.com/maps/api/place/photo?" +
            "maxwidth=400" +
            "&photoreference=" +photoreference +
            "&key="+API_KEY;

Log.d("Loading restaurantpic" , restaurantpic);

    Glide
            .with(mContext)
            .load(restaurantpic)
            .centerCrop()
           // .placeholder(R.drawable.loading_spinner)
            //.crossFade()
            .into(mImageViewIcon);

This is an example of restaurantpic URL with https protocol which gives 500 error. The same with HTTP protocol gives below attached image(Which is for quota filled).

A: So guys, It was my silly mistake to use "referenece" field from the JSON data instead of "photo-reference" field .
The issue was resolved .

A: In case anyone else is having some trouble with this:
If you are trying to use the Web Service API key on Android it will not work correctly if you are also trying to restrict that API key to only certain Android Apps (by package name/fingerprint)
See here:
https://developers.google.com/places/web-service/get-api-key#get_an_api_key
Note: The Google Places API Web Service does not work with an Android or iOS restricted API key.


text:
Q: LIMIT the results of nested JOIN queries I honestly have no idea how to give a better title for this :(
Basically I have these 3 tables
Table "public.users"
Column |         Type          |                     Modifiers
--------+-----------------------+----------------------------------------------------
id     | integer               | not null default nextval('users_id_seq'::regclass)
name   | character varying(40) |
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
Referenced by:
TABLE "comments" CONSTRAINT "comments_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE

Table "public.comments"
Column  |  Type   |                       Modifiers
---------+---------+-------------------------------------------------------
id      | integer | not null default nextval('comments_id_seq'::regclass)
user_id | integer |
content | text    |
Indexes:
"comments_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"comments_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE

Table "public.votes"
Column   |  Type   |                     Modifiers
------------+---------+----------------------------------------------------
id         | integer | not null default nextval('votes_id_seq'::regclass)
up         | boolean | default false
comment_id | integer |
Indexes:
"votes_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"votes_comment_id_fkey" FOREIGN KEY (comment_id) REFERENCES comments(id) ON UPDATE CASCADE ON DELETE CASCADE

I want to select all users (including those who don't have any comment) and include 3 comments for each user and then for each comment select 2 votes (including those comments that don't have any vote)
What I have so far is the query to select 3 comments for each user
SELECT users.id as userId, comments.id as commentId, users.name, comments.content, comments.rn
FROM users
LEFT JOIN (
  SELECT *, row_number() OVER (PARTITION BY comments.user_id) as rn FROM comments
) as comments
ON users.id = comments.user_id
WHERE comments.rn <= 3 OR comments.rn IS NULL;

A: Because users to comments and comments to votes both have 1-to-many relationships, doing both joins will give you CxV (3x2=6) rows per user.
Because comments will be duplicated when a comment has more than 1 vote, use dense_rank() instead of row_number() so that "duplicate" comments will have the same rank and be included in the rn < 4 criteria
select * from (
    select *,
        dense_rank() over (partition by u.id order by c.id) rn,
        dense_rank() over (partition by c.id order by v.id) rn2
    from users u
    left join comments c on c.user_id = u.id
    left join votes v on v.comment_id = c.id
) t where rn < 4 and rn2 < 3

A: You have the right idea.  Just continue with it:
SELECT u.id as userId, c.id as commentId, u.name, c.content, c.rn
FROM users u LEFT JOIN
     (SELECT c.*,
             ROW_NUMBER() OVER (PARTITION BY c.user_id) as rn
      FROM comments c
     ) c
    ON u.id = c.user_id LEFT JOIN
    (SELECT v.*,
            ROW_NUMBER() OVER (PARTITION BY v.comment_id) as rn
     FROM votes v
    ) v
    ON c.id = v.comment_id
WHERE (c.rn <= 3 OR c.rn IS NULL) and
      (v.rn <= 2 or v.rn IS NULL);

A: Probably it will be more index-friendly:
select
  *
from
  users u
    left join lateral (select * from comments c where u.id = c.user_id order by c.id limit 3) c on (u.id = c.user_id)
      left join lateral (select * from votes v where c.id = v.comment_id order by v.id limit 2) v on (c.id = v.comment_id)


text:
Q: Fade 3 divs in and out sequentially I am trying to animate 3 divs one at a time to fade in and out. I would like the first one to fade in, pause for 2 seconds then fade out. Then the second one should fade in, pause for 2 seconds then fade out followed by the third div doing the same. Right now the animation is not working and the divs are not fading in at all. Below is the html and css being used for the animation.

    Rag & Bone
    just for you.

    Asos
    just for you.

    Style inspiration
    just for you.

.fave-content {
  width: 100%;
  height: 544px;
  opacity: 0;

  .fave-animate {
    -webkit-animation-name: demo;
    -webkit-animation-timing-function: ease-in-out;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-duration: 10s;
    -webkit-animation-direction: alternate;

    &.rag-and-bone-container {
      -webkit-animation-delay: 0;
    }

    &.asos-container {
      -webkit-animation-delay: 5s;
    }

    &.style-container {
      -webkit-animation-delay: 10s;
    }
  }

  @-webkit-keyframes demo {
    0% {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }

    100% {
      opacity: 0;
    }
  }

A: Your animation sequence doesn't match the requirement.
This is supposed to happen over 10 seconds
 @-webkit-keyframes demo {
    0% {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }

    100% {
      opacity: 0;
    }
  }

There is no pause here..once the sequence reaches 50% it immediately starts working back to 0 opacity. So the actual sequence should look like...
 @-webkit-keyframes demo {
    0% {
      opacity: 0; /* take 4 seconds */
    }

    40% {
      opacity: 1; /* pauses for 2 seconds (20% of 10 seconds) */
    }

    60% {
      opacity: 1; /* still at full opacity but now resumes taking another 4 second */
    }

    100% {
      opacity: 0;
    }
  }

You can also remove the timing function.

A: Using the & you where telling the css that reg and asos are children of fave when they are not, they are fave.
Here is a sample of three divs behaving in such an animation you should be able to cope with it from here.
http://jsfiddle.net/qdnsz1p8/1/
.fave-animate {
background:red;
padding:60px;
margin-right:10px;
width:40px;
float:left;
-webkit-animation: demo ease-in-out 5s infinite;
}

div.rag-and-bone-container {
  -webkit-animation-delay: 0;
}

div.asos-container {
  -webkit-animation-delay: 5s;
}

div.style-container {
  -webkit-animation-delay: 10s;
}

@-webkit-keyframes demo {
  0% {
    opacity: 0;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}


text:
Q: Cite Author and Number (Index) How I can cite: Author [Number]?. For example:

Wolsey [8]

A: You can achieve this using the natbib package in numerical mode, and its \citet command.
\documentclass{article}
\usepackage[numbers]{natbib}
\usepackage{hyperref}  % Hyperlinks bib references.
\begin{document}

  Here is a reference: \citet{Ca04}.
  \bibliographystyle{plainnat}
  \bibliography{test}
\end{document}

A: I can do it using flexbib package and \cite command:
\documentclass{article}
\usepackage{hyperref}
\usepackage[plain*,spanish]{flexbib} %in this case the document is in spanish
\begin{document}

Here is a reference: \cite{Ca04}.
\bibliographystyle{plainnat}
\bibliography{test}
\end{document}

A: \newcommand\Myciteauthor[1]{\citeauthor{#1} \cite{#1}}

and use \Myciteauthor instead of \citeauthor in your text


text:
Q: Create a new column for the table based on the getSheetCount() I used below code to generate a table based on the uploaded excel. The output is just one column table.
 column A
 1          // sheet1
 2
 3
 A          // sheet2
 B
 C

foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{

    $worksheetTitle      = $worksheet->getTitle();
    $highestRow          = $worksheet->getHighestRow();
    $highestColumn       = "B";
    $highestColumnIndex  = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $nrColumns           = ord($highestColumn) - 64;

        for ($row = 0; $row <= $highestRow; ++ $row)
        {
            echo "
";
            $val = array();
            for ($col = 1; $col < $highestColumnIndex; ++ $col)
            {
                $cell = $worksheet->getCellByColumnAndRow($col, $row);
                echo "".$val[] = $cell->getFormattedValue()."	";
            }
            echo "
";

         }

}

I wanted that every time phpexcel shifts to another sheet in the excel, the data will be moved to the next column based on the getSheetCount().
 //$countSheet = $objPHPExcel->getSheetCount($worksheet); --> output: 2

 column A    column B
 1           A
 2           B
 3           C

How can I achieved this, I've tried several for loop, but still no luck, please help.
I have tried below code but seems not to be working..
                $i = 0;
                $row = 0;
                $column = count($worksheet->getHighestColumn());
                $maxcols = $column;

                echo "
";

                echo "
";

                while ($row < $column)
                {

                    if ($i == $maxcols) {
                        $i = 0;
                        //echo "

";
                    }

                //echo "hello	";

                /********************************************/

            foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
            {

                        $worksheetTitle             = $worksheet->getTitle();
                        $highestRow                     = $worksheet->getHighestRow();
                        $highestColumn              = $worksheet->getHighestColumn();
                        //$highestColumn                = "B";
                        $highestColumnIndex     = PHPExcel_Cell::columnIndexFromString($highestColumn);
                        $nrColumns                  = ord($highestColumn) - 64;

                        for ($row = 0; $row <= $highestRow; ++ $row)
                        {

                                //echo "
";

                                    $val = array();
                                    for ($col = 1; $col < $highestColumnIndex; ++ $col)
                                    {
                                        $cell = $worksheet->getCellByColumnAndRow($col, $row);
                                        echo "".$val[] = $cell->getFormattedValue()."	";
                                    }

                                //echo "
";
                        }

            }

                /********************************************/

                    $i++;
                    $row++;

                }

                while ($i <= $maxcols) {
                    //echo " 	";
                    $i++;
                }

                echo "
";
                echo "
";

A: You need to store the values of all worksheets first (per row) before using echo something like
$val1[] = $cell->getFormattedValue(); // this should go in a foreach worksheet loop
Then echo with
echo "
";
foreach($value1 as $value){
   echo '' . $value . '	';
}
echo "
";


text:
Q: Angular ag-grid after update in my app, doesn't refresh the data I recently encountered an issue, updating the ag-grid in angular. I am working with Asp.net core as backend and angular as frontend. Although I'm not using cache, it seems the page caches the grid's source data. After refreshing the page with shift+F5, yet grid is not updated. However, after opening a new page (new session), grid shows updated data. I have tried a few things, but I couldn't solved it.
What should I check for solving the issue? Any help is appreciated.


text:
Q: Custom args for each instance of Chrome when running parallel tests with Protractor Is it possible to pass custom args for each instance of Chrome when running parallel tests in Protractor? I need to know the Remote debugging port for each instance so I can connect with the Dev Tools protocol.
As I see it there's two options. Set the port to a specific unique value for each instance, or let it be set automatically and fetch it somehow when preparing the tests. Would it be possible with any of these options?
exports.config = {
    framework: 'jasmine',
    chromeDriver: chromeDriverPath,
    multiCapabilities: [{
        browserName: 'chrome',
        chromeOptions: {
            args: process.env.HEADLESS && puppeteer ? ['--headless',  `--remote-debugging-port=${DEV_TOOLS_PORT}`] : [`--remote-debugging-port=${DEV_TOOLS_PORT}`],
            binary: puppeteer.executablePath()
        },
        shardTestFiles: true,
        maxInstances: 1
    }]
}

A: If I got the problem right, what you could do is to pass parameters as env variables to protractor on start. So your config would look like this:
exports.config = {

    framework: 'jasmine',
    chromeDriver: chromeDriverPath,

    multiCapabilities: [{
      'browserName': 'chrome',
      'chromeOptions': {
        args: [`--remote-debugging-port=${process.env.PORT_ONE}`]
      }
    }, {
      'browserName': 'chrome',
      'chromeOptions': {
        args: [`--remote-debugging-port=${process.env.PORT_TWO}`]
      }
  }]
}

And then start your protractor process with env variables like so:
PORT_ONE=90 PORT_TWO=80 protractor protractor.conf.js

A: One of the two options are solved. But I would still like to know if there's a possibility to use custom args for each instance.
// Get Remote debugging port for chrome
let chromeRemoteDebuggingPort;
browser.getCapabilities().then((capabilities) => {
    const chromeOptions = capabilities.get('goog:chromeOptions');
    if( chromeOptions && chromeOptions.debuggerAddress) {
        chromeRemoteDebuggingPort = chromeOptions.debuggerAddress.split(':')[1];
    }
});


text: Q: How to auto-refresh KDE desktop? If I add or remove files from my desktop on KDE by using, for instance, a terminal or Dolphin, the desktop isn't automatically refreshed. It's missing the new files and still shows the removed files. I can right-click the desktop and choose "Refresh Desktop". Is there any way to keep the desktop refreshing automatically?


text:
Q: javascript settimeout different result on firefox and chrome i have just test a settimeout and setInterval method on firefox and chrome.
but i found some different look on the result.
so hope somebody can explain to me the logic.
because now i getting some bug and i suspect on it.
function test() {
    var i = 0;
    setTimeout(function () {
        i = 10;
    }, 4);
    setInterval(function () {
        i++;
    }, 4);
    alert("alert");
    alert(i);
}
test();

above is a simple js code. the result on firefox usually is 11, but something is 0.
in chrome, the result always is 0;
so what cause the result so different ?
any idea ?


text:
Q: Which container should I use to quickly find an element, knowing that by construction it's already ordered? I have to use a container that by construction is already ordered and I need a quick find-function.
My idea is to use a set to exploit its set.find, which should be quick enough, but constructing my set with set.insert could be slow because I already know that the elements are ordered!
For this part, I could just use a vector with vector.push_back, but then I should write the find function myself and it would also be slower than the set::find... What do you suggest me?
EDIT:

*

*The container needs to be modified, but will always be ordered, and its size will always be the same (but i don't know it a priori)

*No repeated values.

*A lot more finds than inserts.

*I just need to know if it exists, not its position.

*I found the std::binary_search. Is it good?

A: Constructing a set from a pair of iterators is guaranteed to be O(N) if the input range is already sorted, so you could just use that. (See e.g. http://en.cppreference.com/w/cpp/container/set/set.)
Subsequent inserts are O(log N).
Although if the total size is not that large a sorted vector tends to beat everything else because it is so cache friendly. std::binary_search is O(log N), the same as set::find.
std::unordered_set doesn't care about your ordering, but does give you O(1) lookup (on average, no guarantees).

A: std::vector with std::make_heap(), push_heap(), pop_heap() and sort_heap() could help you to deal with it as fast as std::set. However, you'll need to use std::binary_search manually.


text:
Q: How to specify a connection point for an element in which connectors can link there in Enterprise Architect? It's possible to define a shape for a stereotype in Enterprise Architect. How is it possible to specify an exact point on that shape to link incoming/outgoing connectors?
For example, connectors can be linked to a "Gateway" only on its corners, not to any other position on the edges. How are those corners defined as the only entry/exit point?

A: I don't think you can. I'm not aware of any shape script properties you can set to achieve this.
The BPMN Gateway is a stereotyped UML Decision, and the connectors-at-corners-only behaviour is inherited from that (you can test this in a regular Activity diagram). I think EA handles these differently from other elements in a way which cannot be controlled from a shape script.
Of course, you can always create your own Decision stereotype and get the same result, but semantically that might not be what you're after.


text:
Q: Laravel 5.5 multi language application I followed this article on how to make your site multi language.
But I don't understand why I always get an error when I surf to hoemstead.app/lang/en for example.
The error:

Sorry, the page that you're looking for does not exist

My LanguageController
use Config;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;

class LanguageController extends Controller
{
    public function switchLang($lang)
    {
        if (array_key_exists($lang, Config::get('languages'))) {
            Session::put('applocale', $lang);
        }
        return Redirect::back();
    }
}

My routes:
Route::get('lang/{lang}', ['as'=>'lang.switch', 'uses'=>'LanguageController@switchLang']);

My Language Middleware
use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;

class Language
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Session::has('applocale') AND array_key_exists(Session::get('applocale'), Config::get('languages'))) {
            App::setLocale(Session::get('applocale'));
        }

        return $next($request);
    }
}

I've also added this middleware to my Kernel.php file
My Languages.php file in the config folder
return [
    'en' => 'English',
    'nl' => 'Nederlands',
    'fr' => 'Français',
];


text:
Q: Modify SQL query to filter results I would like to modify the function below to filter records in the table that have column "type" equal to "hod"
 public function getHOD() {

        $query = $this->pdo->prepare('SELECT * FROM `' . $this->table . 'WHERE type=hod`;');
        $query->execute();

        if ($query->rowCount() == 0) return null;

}

I am having trouble figuring out how to add WHERE type=hod into the query?

A: Here are multiple things that you need to fix:

*

*You added ` before table name, but not after

*You need a space before WHERE

*You need to add ' around hod
If I did not miss anything your query should look like this:
$query = $this->pdo->prepare("SELECT * FROM `" . $this->table . "` WHERE type='hod'");

A: Use in quotes
$query = $this->pdo->prepare("SELECT * FROM `" . $this->table . "` WHERE type='hod'");

A: It looks like a space is missing in 'WHERE, which should say ' WHERE.
And hod, if it's a string should have quotes in SQL.

A: Try this
$query = $this->pdo->prepare("SELECT * FROM `" .$this->table. "` WHERE type='hod'");


text:
Q: Adding header/column to my .csv file My current code:
file='filelocation.sav'
finalfile = 'filelocation.csv'

s=spio.readsav(file, python_dict=True, verbose=True)
amf=np.asarray(s["amf"])

d=[amf]
df=pd.DataFrame(data=d)
df=df.T
df.to_csv(finalfile,sep= ' ', encoding = 'utf-u', header=True)

This is my current output
I would like my output to look like this:
   amf
0  6.685
1  6.84
2  7.0
3  7.16
4  7.33
5  7.51
6  7.70

etc. Basically I want the header to line up with the data it represents so that I can properly call upon said data and plot.
Another issue I noticed was that when I asked jupyter with
file.columns

to tell me the index, I was returned this output:
Index([u' 0 1 2 3 4 5 6'], dtype='object)

which leads me to believe that there is only one index being accounted for, when I'd like to have 7 specific indices (including "0").

Edited past here:
So: It looks like another issue I'm having is that although the number of rows I intend to have is about 87000 in length, it's showing through as having 87000 columns.
Looks like I need to make some changes to that my array "amf" is created as a row and not a column.

A: The problem is that your are wrapping amf between brackets df=[amf] making it a list of arrays, change it to df=amf, for instance:
data = [np.array([6.685, 6.84, 7.0, 7.16, 7.33, 7.51, 7.70])]
result = pd.DataFrame(data=data)
print(result.shape)

returns: (1, 7) that is 1 column and 7 rows, however:
data = np.array([6.685, 6.84, 7.0, 7.16, 7.33, 7.51, 7.70])
result = pd.DataFrame(data=data)
print(result.shape)

returns (7, 1), also you need to set the columns of the DataFrame:
import numpy as np
import pandas as pd

data = np.array([6.685, 6.84, 7.0, 7.16, 7.33, 7.51, 7.70])
result = pd.DataFrame(data=data, columns=['amf'])
print(result)

Output:
   amf
0    1
1    2
2    3
3    4
4    5
5    6


text:
Q: Block SIGINT from terminating program I need some help on C program - it is a reverse shell (https://github.com/arturgontijo/remoteShell/blob/master/reverseShell.c) I made few changes, like put that all in a loop and some sleep pattern + put some argument to pass directly IP and PORT now that thing works very good it's stable (problem that cannot autocomplete stuff with TAB I don't really care) BUT what I really care is that this thing will break if on target machine I press CTRL+C the program just exits itself. Now I used this example to block CTRL+C calls:
/* Signal Handler for SIGINT */
void sigintHandler(int sig_num)
{
    /* Reset handler to catch SIGINT next time.
       Refer http://en.cppreference.com/w/c/program/signal */
    signal(SIGINT, sigintHandler);
    printf("\n Cannot be terminated using Ctrl+C \n");
    fflush(stdout);
}

signal(SIGINT, sigintHandler);

I got this example online and put it on my loop as well, but still from client pressing ctrl+C breaks program. I wonder dup2() is responsible for that or something because on simple C program this actually worked fine.

A: You can use the sigetops family of functions to manipulate the signals sent into your application.
So for your example you could use:
#include <signal.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    sigset_t block_set;

    sigemptyset(&block_set);

    sigaddset(&block_set, SIGINT);

    sigprocmask(SIG_BLOCK, &block_set, NULL);

    while(1) {
        sleep(1);
    }
}

Running Example: https://repl.it/repls/RelevantImaginarySearchservice
You can unblock the signal at a later time by calling
sigprocmask(SIG_UNBLOCK, &block_set, NULL);


text:
Q: what's efficient way to filter an array I am programming c on linux and I have a big integer array, how to filter it, say, find values that fit some condition, e.g. value > 1789 && value < 2031. what's the efficient way to do this, do I need to sort this array first?
I've read the answers and thank you all, but I need to do such filtering operation many times on this big array, not only for once. so is iterating it one by one every time the best way?

A: If the only thing you want to do with the array is to get the values that match this criteria,  it would be faster just to iterate over the array and check each value for the condition (O(n) vs. O(nlogn)). If however, you are going to perform multiple operations on this array, than it's better to sort it.

A: You could use a max heap implemented as an array of the same size as the source array. Initialize it with min-1 value and insert values into the max-heap as the numbers come in. The first check would be to see if the number to be inserted is greater than the first element, if it's not, discard it, if it is larger then insert it into the array. To get the list of numbers back, read all numbers in the new array till min-1.

A: Sort the array first. Then on each query do 2 binary searches. I'm assuming queries will be like -
Find integers x such that a < x < b

First binary search would find the index i of the element such that Array[i-1] <= a < Array[i] and second binary search would find the index j such that Array[j] < b <= Array[j+1]. Then your desired range would be [i, j].
This algorithm's complexity is O(NlogN) in preprocessing and O(N) per query if you want to iterate over all the elements and O(logN) per query if you just want to count the number of filtered element.
Let me know if you need help implementing binary search in C. There is library function named binary_search() in C and lower_bound() and upper_bound() in C++ STL.

A: To filter the array, you'll have to look at each element once. There's no need to look at any element more than once, so a simple linear search of the array for items matching your criteria is going to be as efficient as you can get.
Sorting the array would end up looking at some elements more than once, which is not necessary for your purpose.

A: If you can spare some more memory, then you can scan your array once, get the indices of matching values and store it in another array. This new array will be significantly shorter since it has only indices of values which match a specific pattern! Something like this
int original_array[SOME_SIZE];
int new_array[LESS_THAN_SOME__SIZE];

for ( int i=0,j=0; i<SOME_SIZE; i++)
{
    if ( original_array[i]> LOWER_LIMIT && original_array[i]< HIGHER_LIMIT )
    {
        new_array[j++] = i;
    }
}

You need to do the above once and form now on,
for ( int i=0; i< LESS_THAN_SOME_SIZE; i++ )
{
    if ( original_array[new_array[i]]> LOWER_LIMIT && original_array[new_array[i]]< HIGHER_LIMIT )
    {
        printf("Success! Found Value %d\n", original_array[new_array[i]] )
    }
}

So at the cost of some memory, you can save considerable amount of time. Even if you invest some time in sorting, you have to parse the sorted array every time. This method minimizes the array length as well as the sorting time ( at the cost of extra memory, of course :) )

A: Try this library: http://code.google.com/p/boolinq/
It is iterator-based and as fast as can be, there are no any overhead. But it needs C++11 standard. Yor code will be written in declarative-way:
int arr[] = {1,2,3,4,5,6,7,8,9};

auto items = boolinq::from(arr).where([](int a){return a>3 && a<6;});
while (!items.empty())
{
    int item = items.front();
    ...
}

Faster than iterator-based scan can be only multithreaded scan...


text:
Q: gem command raises UnsatisfiableDependencyError in rails project folder, but works with sudo, or when called from another folder I have a rails project in the myapp folder.
# in my_app folder
$ gem -v
...
ruby/2.1.0/rubygems/resolver.rb:406:in `resolve_for_zero': Unable to resolve dependency: 'rails (= 4.1.5, = 4.1.5)' requires 'bundler (< 2.0, >= 1.3.0)' (Gem::UnsatisfiableDependencyError)
...
$ sudo gem -v
Password:
2.4.2

# revoke sudo privileges
$ sudo -k
$ cd
# in home directory now
$ gem -v
2.4.2

The Gemfile of my rails project is here and the Gemfile.lock is here. I realize this has something to do with the Gemfile, but have no idea how to fix it.
There is a fix for a similar, but worse issue #886 in rubygems 2.4.2 with this commit . I have upgraded to rubygems 2.4.2 (I had to use sudo gem update --system as gem update --system gave the same error at the time), but the current issue still persists.

A: I had previously fixed a closely related rubygems problem by setting export RUBYGEMS_GEMDEPS=- in my .bash_profile, which was causing this error.  that issue has since been fixed with an update, and this bash setting was causing the current problem described above. Removing this line from .bash_profile fixed the problem.


text:
Q: Kakeya problem and arithmetic progressions Here's something I also posted on Stackexchange recently. It's very related to the Kakeya problem, yet I fail to see why this is true. It goes like this:
Let $r > 2$ be an integer parameter. Let $K \subset [N]=1,\ldots,N$ be a set containing arithmetic progressions of length $r$ in at least $N' \leq N/r$ (up to some constant) different dirrections ($b$ is the integer of the arithmetic progression $a,a+b,a+2b,\ldots$). Then, for every $r$, show that there exists a set $K$ as above of size at most $N^{1-\epsilon_{r}}$ with $\epsilon_{r} > 0$ a constant depending only on $r$.
I am kind of confused b/c I read some time ago about some result of J. Bourgain which basically said that a similar conclusion would give the validity of the general Kakeya, so I feel this is very hard, yet I got it as an exercise, so I'm probably missing something. Also, it would be very nice if someone can give some references about Bourgain's result which I'm talking about - I can't find it anywhere. Thanks
PS. can't login into the old account.


text:
Q: Show options based on selected value <select id="prodi" name="product_names" style="padding:6px;">
  <?php
    $resultsTicket = $mysqli->query("SELECT
                                     product_list.product_name,
                                     product_package.size
                                     FROM product_list
                                     LEFT JOIN  product_package
                                     ON product_list.product_code = package.product_code
                                     ORDER BY   product_list.id ASC");
    $orders = array();
    if ($resultsTicket) {
        while($obj = $resultsTicket->fetch_object()) {
            $orders[$obj->size][$obj->product_name]  = array(
                'product_name' => $obj->product_name,
                'size' => $obj->size,
                'status' => $obj->status);
        }
        foreach ($orders AS $order_id => $order) {
            foreach ($order AS $item => $data) {
    echo '<option value="'.$obj->product_name.'">' . $data['product_name'] . '</option>';
            }
        }
    echo '</select>
';
    echo '

          Package
          <select name="packageInfi" style="padding:6px;">';
    }
    echo '<option value="">'.$order_id.'</option>';
    echo '</select>
';
    ?>

What I am going to do with my code above is to get the size/package based on the product name which has been selected
Here is the place where I will choose the product name: echo '<option value="'.$obj->product_name.'">' . $data['product_name'] . '</option>';
And here is the place where the package should showing up based on the product has been selected above: echo '<option value="">'.$order_id.'</option>';
But instead of showing up the package based on the product which has been selected, it only shows me the last package of the products.
Here is the sketch of the products:
      -------------------------------------------
      no       product_name     product_code
      -------------------------------------------
      1        product_one      001
      2        product_one      002
      3        product_one      003
      4        product_one      004

      -------------------------------------------------
      product_code         package     price
      -------------------------------------------------
       001                  2kg        10
       001                  3kg        20
       001                  4kg        30
       001                  5kg        40

       002                  6kg        50
       002                  7kg        60
       002                  8kg        70
       002                  9kg        80

From the first table, I only want to get the data of the all products name, while from the second table I want to get the size and the price of each products.

A: echo '<option value="'.$obj->product_name.'">' . $data['product_name'] . '</option>';

$obj->product_name is out of the loop. so this is the reason your getting only the last. I believe this should be also $data['product_name']


text:
Q: Rendering an isometric map in java with individual rectangles I've been researching for the past hour or so and I can't seem to render an isometric map. I want to achieve something like this.
But I am getting this.... I am storing my map as tiles in a 1 dimensional array like so:
private final int width, height;
    private final int tileWidth, length;
    private int[] tiles;

    public Level(int width, int height) {
        this.width = width;
        this.height = height;
        tiles = new int[width * height];
        tileWidth = 68;
        length = 48;
    }

I am passing through 10, 10 as the parameters for width and height. And I render the map like so:
public void render(Graphics g) {
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                g.setColor(Color.red);
                if (x % 2 == 0)
                    g.drawRect(x * tileWidth, y * length / 2, tileWidth, length);
                else
                    g.fillRect((x * tileWidth) + (tileWidth / 2), (y * length / 2), width, length);
            }
        }
    }

Any help would be really appreciated, I've wanted to learn to make isometric games but have been stuck with flat 2D for a while.

A: For just tiles, you could use a shear transform:
Graphics2D g2d = (Graphics2D) g;
AffineTransform at = AffineTransform.getShearInstance(1, 0);
g2d.transform(at);
// rest of your drawing code here

You may also want to set the shear anchor point:
double sa_x = 100, sa_y = 100; // or whatever
AffineTransform at = new AffineTransform();

// S3: Move back to original origin
at.translate(sa_x, sa_y);

// S2: Shear
at.shear(1, 0);

// S1: Set origin
at.translate(-sa_x, -sa_y);

You can vary the shear factor 1 to get different amounts of shear.

A: Instead of drawing rects, you need to draw lines at isometric angles.
The angles in isometric geometry are 30 degrees, 90 degrees, 150 degrees, 210 degrees and 270 degrees (in radians: pi/6, pi/2, 5pi/6, 7pi/6, 3pi/2, 11pi/6.).
cos(pi/6) is sqrt(3)/2 or 0.866... and sin(pi/6) is 1/2 or 0.5. (This is meaningful because of http://en.wikipedia.org/wiki/File:Sin-cos-defn-I.png )
This means that if you want to draw a line at the angle pi/6 that is D pixels long starting at x1,y1:
x2 = x1+cos(pi/6)*D e.g. x1+D*sqrt(3)/2
y2 = y1+sin(pi/6)*D e.g. y1+D/2

and draw from x1,y1 to x2,y2.
All the other angles are either reflections of this (one dimension or both are made negative) or straight up and down (trivial to draw).
To calculate where on the screen to draw an isometric object, consider that isometric geometry has three dimensions: X, Y, Z. Movement by Z will just make you draw D higher or D lower. Movement by X or Y will move you in one isometric angled direction or the other, by the same x and y as the distance of drawing one tile line in that direction (so similar formula to the above).


text:
Q: Deleting a cell in tableview, the cell also can be reused,why?  at first,i delete one cell in tableView,then i want to add another new cell in the tableView,but the  new cell is not new,it is just the cell which i delete. i know what dequeueReusableCellWithIdentifier means.i think when  delete one cell,the cache in dequeueReusableCellWithIdentifier is also deleted.why not?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"table reload");

    PDFModel* tempmodel=[PDFArray objectAtIndex:indexPath.row];
    NSString * CellIdentifier=tempmodel.PDFName;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSLog(@"cell %x",cell);
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
       //custom the cell
        cell.text=...
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete)
    {
         [PDFArray removeObjectAtIndex:indexPath.row];
         NSMutableArray* array=[[NSMutableArray alloc] init];
         [array addObject:indexPath];
         [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];

    }
}

A: Your question is a bit weird, but I guess you're wondering what the following code does?
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

What the code does, is that it tries to retrieve a cached UITableView cell. This is to reduce memory usage on the iPhone.
Once you delete a cell, you should also remove the data from the datasource (usually an array), e.g.:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
       if (editingStyle==UITableViewCellEditingStyleDelete)
       {
           // remove object from array ...
           [dataArray removeObjectAtIndex:indexPath.row];
       }
}

(Remember: you can only remove items from an NSMutableArray at runtime, not from a NSArray)
If the cell gets redrawn, you will first check which cell needs to be redrawn, then you retrieve the appropriate data from the datasource, this is all done by the UITableViewDataSource delegate methods. You only have to make sure to retrieve the right content from the array and update the cell's content on redraw, e.g. like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        // no cached cell is found, create a new cell ...
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        // add some defaults for cells in the initializer,
        // stuff that's done here should be important for
        // all displayed cells, for example background image.
    }

    // update the cell's content, e.g.: - it will only display content that's currently in the array, deleted objects shouldn't exist in the array at this point
    NSString *title = [dataArray objectAtIndex:indexPath.row];
    [cell.textLabel setText:title];

    return cell;
}

A: I think You can use
NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d",indexPath.row];
instead of
NSString * CellIdentifier=tempmodel.PDFName;
please replace it & check it. I think it's helpful to you.

A: There's no reason to delete the UITableViewCell since it can be reused. That cell won't be displayed until it is processed again by cellForRowAtIndexPath, so it won't show up with the old data. The laid-out cell, though -- the view and all of its subviews -- can be reused after new data replaces the old data.
Think of it like each cell is a whiteboard (dry erase board) where it's cut down to a certain size and all of the basic information areas are etched into the surface: a place for some text, another area for a number, a special space for drawing a picture, etc. In tableView:cellForRowAtIndexPath: when you check whether the cell == nil, you're trying to find out if there are any already-etched whiteboards available that you can erase and write the new information on with your dry erase marker. If there aren't then it cuts out and etches a brand new board to write information on, but if there is one that can be erased then it just wipes off the old information with an eraser and writes in the new information. As you can imagine, this saves a lot of time.
When a user is scrolling the table what's actually happening is that when one cell (whiteboard) scrolls off the top and is no longer visible, the system erases the data and moves it to the bottom of the stack; it will be the next one to scroll into view. As a result the system only has to create as many whiteboards as can be visible at any one time -- the ones off-screen don't actually exist.
When you delete a cell all you're really doing is telling the table to (a) stop displaying that cell, and (b) setting a flag so the table can use the eraser to wipe off the old data but still reuse the whiteboard.
Creating cells can be very costly in terms of computing power. If a UITableView had to create a new cell every time one came into view while the user was scrolling -- in the analogy, if it had to cut out a new whiteboard and etch all of the areas into it every time one came into view -- the scrolling would be very jerky and look terrible. By reusing cells, replacing just the changing contents, the table can move smoothly as the user interacts with it.

A: You seem confused by the difference between deleting a cell (an objective-c UI object) and the data it displays.

*

*When you allow a user to delete a cell in the user interface you need to delete the corresponding data from your data model

*The implementation of UITableView is highly optimized in iOS and it caches cells (UI objects) to improve performance. You don't really need to be concerned about this as your table will be optimally loaded and displayed based on your data.
In tableView:cellForRowAtIndexPath: you do the following:

*

*Attempt to dequeue a cell instance. This takes advantage of caching done by UITableView

*If dequeue does not return a cell, create a new one.

*Once you have a cell, configure it with the appropriate data from your data model

*When a user chooses a delete action from a cell, delete the data from your data model. optionally, you can animate removing the cell from the table or simply reload the whole table.
The specifics of #4 depend on the user interface you want and how you've configured your data model.
The Apple docs are pretty good about explaining this.
http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html


text:
Q: What's the difference between Chocolatey, OneGet, PsGet, NuGet, ...? I know there are many package sources for PowerShell extensions. I'm seeking for a comprehensive answer, how:

*

*Chocolatey

*NuGet

*PsGet

*PowerShellGallery

*OneGet

*MyGet

*ProGet

*...

all these fit together into one big picture. Please denote discontinued or subsumed versions.
According to this post: Difference between Chocolatey and NuGet NuGet is only integrated in VisualStudio and meant for .NET libraries.

A: OneGet has been renamed to Package management. Its core provides you with discovery and installation/uninstallation of various packages. OneGet is often referred to as a "package manager manager".
OneGet is a part of WMF 5 installation. Think of this as the "central concept" in the big picture. Now let's talk about packages.
Packages are fetched through package providers. E.g. PowerShellGet is one package provider for OneGet. Powershell gallery is a package source of of PowershellGet (PSGet). A provider can have multiple sources where it can search for its packages.
E.g for the nuget-package provider; you can easily add the sources to the public nuget gallery and register your own e.g. myget source so it can be used when searching for packages.
Chocolatey is just another example of a package provider. Earlier it had to be installed and was a seperate module with its own logic. The new Chocolatey provider conforms to the new framework of installing / managing packages.
So on a more conceptual level; a package provider itself contains information on how to install and search its sources (sources can be registered/unregistered for each and every provider); whilst OneGet (Package management, package manager manager) works on the level above, managing package providers and interfacing this all for you.
OneGet glues it all together; while the providers itself knows how to handle packages based on its registered sources.
Hope this explains it on the conceptual level.
See also this nice blogpost here explaining a few things more in detail:  10 things about OneGet that are completely different than you think.
If you want to play around with package providers and sources :
 Get-PackageProvider # -Shows package providers installed on your machine)
 Find-PackageProvider # -Find online package providers you can pull down and install)
 Get-PackageSource # -List all package sources, with its provider name)
 Register-PackageSource # -Register new package source for a provider)

These are just some examples. Get a more extensive list by invoking the following command:
Get-Command -Module PackageManagement


text:
Q: Duplication of list while opening multi page using node JS I build an html page linked to a node server.
This page include a hypertext list which is duplicated while other page are opened from the server. I don't want this functionning, the list don't have to be duplicated while other pages are opened.
I test some code, as : list.removeChild  or  list.replaceChild  but the list disappear..
what I want to modify in order to not duplicate the list is :
                    var list = document.getElementById("messagesList");
                    socket.on('messageFromServer', function (data) {
                    var item = document.createElement('li');
                    item.innerHTML = data.network;
                    list.appendChild(item);
                    });

Thanks for any help.
Here is the html full code :

<!DOCTYPE html>

        <meta name="description" content="Interface de Start and Stop du TrainLab" />
        <meta name="Copyright" CONTENT="Alstom" />
        <meta name="expires" CONTENT="never" />
        <meta name="audience" CONTENT="all" />
        <meta name="Language" CONTENT="Fr" />

       <title>H M I</title>
       <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
       <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
       <link rel="stylesheet" media="screen" type="text/css" title="Design" href="form.css" />
       <link rel="SHORTCUT ICON" href="favicon.ico">

  Interface

                <form action="/switchoff" method="post">
                    <input type="image"  alt="Off Button" src="pictures/off2.png" class="favorite img2" title="OFF" alt="  "/>
                </form>

Doors

Light

Announcements

                    <form action="/upload" method="post">
                        <input title="Clic to open upload page" class="favorite styledupload" type="submit" id="state" value="Click here to open upload section">
                    </form>

                    <form action="/help" method="post">
                        <input title="Clic to open help page" class="favorite styledhelp" type="submit" id="state" value="Help">
                    </form>

                    <form action="/refresh" method="post">
                        <input title="Clic to refresh page" class="favorite styledrefresh" type="submit" id="state" value="Refresh">
                    </form>

A: I try that : adding " li.remove(); "   at the end of the considered bloc like that :
                    var list = document.getElementById("messagesList");
                    socket.on('messageFromServer', function (data) {
                    var item = document.createElement('li');
                    item.innerHTML = data.network;
                    list.appendChild(item);
                    li.remove();
                    });

the result is interesting because there is no duplication of the list while I open 1 or 2 or 3 other pages, but the list is reduce to 1 line. What's wrong ??


text:
Q: Why do I get nullable reference errors when generating a model using Entity Framework Core in a .NET Core 3.1 console app? I have a C# based .NET Core 3.1 console application. I've installed Entity Framework Core and generated a DB model.
Now I'm getting the following error:

Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater

When I go to the Project -> Properties -> Build -> Advanced..., I see:

Why Can't I select a different C# Version?

How do I either correct this error? How do I upgrade my language version of C#?
Is there a way to manually force it to C# 8 by updating the project file manually?

A: If your project targets .Net Core 3.1 it should support using C# 8.
You can tell compiler specifically which language version to use adding
<LangVersion>8</LangVersion>

statement next to the <TargetFramework> in your csproj file. Then the compiler will tell you, if there are any problem.
Make sure your have .Net Core 3.1 SDK installed.


text:
Q: Issue with the connectionstring when executing with VSCode I have VS2017, ASP.NET CORE, VS Code and SQL Server 2014 installed on my development environment.
I downloaded the sample code from the link: https://github.com/mmacneil/ASPNetCoreGraphQL and then opened it using VSCode.
I created a database with name NHLStats and updated the connectionstring to
"NHLStatsDb": "Data Source=.;Initial Catalog=NHLStats;Trusted_Connection=True;MultipleActiveResultSets=true"

Based on the instructions mentioned in the README.md document, I navigated to the root of the \NHLStats.Api folder and then executed the CLI dotnet run command.
On running the above command I see the below error:

Application startup exception: System.ArgumentNullException: Value cannot be null.
  Parameter name: connectionString
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
  at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action1 sqlServerOptionsAction)
         at NHLStats.Api.Startup.<>c__DisplayClass4_0.<ConfigureServices>b__0(DbContextOptionsBuilder options) in C:\Temp\ASPNetCoreGraphQL-master\src\backend\NHLStats.Api\Startup.cs:line 31
         at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory[TContext](IServiceProvider applicationServiceProvider, Action2 optionsAction)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
         at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
         at NHLStats.Api.Startup.<>c__DisplayClass4_0.b__1(Type type) in C:\Users\sapatro\Learning\GraphQLDetails\ASPNetCoreGraphQL-master\src\backend\NHLStats.Api\Startup.cs:line 41
         at GraphQL.FuncDependencyResolver.ResolveT
         at NHLStats.Api.Models.NHLStatsSchema..ctor(IDependencyResolver resolver) in C:\Temp\ASPNetCoreGraphQL-master\src\backend\NHLStats.Api\Models\NHLStatsSchema.cs:line 11
         at NHLStats.Api.Startup.ConfigureServices(IServiceCollection services) in C:\Temp\ASPNetCoreGraphQL-master\src\backend\NHLStats.Api\Startup.cs:line 41
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
         at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
         at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
         at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()


text:
Q: Product URL in a shared shopping cart in Magento multi-store websites I have Magento multi-store websites that I want that the user will be able to add products to his shopping cart from all the website and pay once.
I successfully done it using this article.
But when the user click on the product in the shopping cart, he is not redirected to the right website. It's a limitation the described in the article at the end.

The link for editing items in the cart will redirect customer to
  original cart website. It is possible to change it, you can override
  getUrl method for cart items block or override controller.

I couldn't find any explaination to how to do this override.
Someone can help me do this?
Thanks

A: In my case i seen file of cart's item.phtml, it was using getproducturl().
So, I modified that method in file /app/code/core/Mage/Checkout/Block/Cart/Item/Renderer.php line 152.
I made condition that if its main website don't change otherwise it adds stores code in url like www.example/store1/Producturl.
I hope This will Help You.
As You Require The File method. Check belowed code.
    public function getProductUrl()
        {
            if (!is_null($this->_productUrl)) {
                return $this->_productUrl;
            }
            if ($this->getItem()->getRedirectUrl()) {
                return $this->getItem()->getRedirectUrl();
            }

            $product = $this->getProduct();
            $option  = $this->getItem()->getOptionByCode('product_type');
            if ($option) {
                $product = $option->getProduct();
            }
            $webids = $product->getWebsiteIds();
            $wid = array();
            foreach($webids as $webid){
                $wid[] = $webid;
            }
            if(!in_array(1,$wid)){
                $website = Mage::app()->getWebsite($wid[0])->getCode();
                $org_url = $product->getUrlModel()->getUrl($product);
                $mod_url = str_replace("www.example.com/index.php/","www.example.com/".$website."/index.php/",$org_url);
                return $mod_url;
            }
            return $product->getUrlModel()->getUrl($product);
        }

As my first website id was "1", that's why i used in_array(1.$wid). You Can use your main website id over there. and in str_replace u can use baseurl() method of main website instead of static value i used.


text:
Q: Oracle - Excluding certain packages from recompiling using DBMS_UTILITY.compile_schema Is it possible to exclude certain packages from the DBMS_UTILITY.compile_schema command? Even though setting the parameter to FALSE only recompiles invalid objects, I want to be sure that certain packages are forever excluded to prevent dependencies errors.

A: One solution is to use a script to generate the compiles exclduing the ones. E.g.
DECLARE
  CURSOR c1 IS
    SELECT object_name, object_type
    FROM user_objects
    WHERE status = 'INVALID'
    AND   object_name NOT IN ( 'EXCL_OBJ1', .... );
  cmd  VARCHAR2 (1000);
BEGIN
  FOR r1 IN c1 LOOP
    -- You will need logic here to cater for different
    -- command e.g. PACKAGE and PACKAGE BODY
    cmd := 'ALTER ' || r1.object_type || ' ' || r1.object_name || ' compile';
    EXECUTE IMMEDIATE cmd;
  END LOOP;
END;

I usually have a repeat loop to count the invalid objects and exit when the count is the same for 2 consecutive loops.
Note that you will need some logic to cater for different compile command syntax between PACKAGE headers and bodies.


text:
Q: c# Copy content of a textbox to Clipboard in browser SharePoint I have a button "copy" which should copy a before generated text to clipboard.
I have the following code in my SharePoint-WebPart-Application:
public void CopyToClipboard_Click(object sender, EventArgs e)
    {
        string text = TextBox1.Text;
        ScriptManager.RegisterStartupScript(CopyButton, CopyButton.GetType(), "Copy", "clipboardData.setData('text', '" + text + "');", true);
    }

The weird thing is that, when I insert my own text in the TextBox1 and press the CopyButton, the text will be copied, but if I want to copy the generated text to the clipboard, nothing happen.

ok,
The problem is not really solved. The functionality copy to clipboard is done, but through removing the escape sequences, the text is not formatted: no new lines, the text is in a row.

A: I would forget about the postback and add an event handler on the textbox for when it loses focus and then use javascript to copy the contents to the clipboard (and remember, some users can prevent this from happening).
See this SO question for answers on the code to copy to the clipboard via javascript.

A: I fixed the problem by removing the escape sequences in the generated text with text.Replace("/n", "").


text:
Q: Compute pairwise distances between two layers: gDistance(byid = TRUE) but pairwise? In R, I have polygon layer A and point layer B. Both have the same number of features, there is one-to-one correspondence (pairing): each polygon of the layer A has a corresponding point in layer B and vice versa.
How do I compute pairwise distances between these pairs of features?
I tried to use
gDistance(A, B, byid = TRUE)

but this will compute the whole NxN matrix, which is huge overhead (I would only use the diagonal of that matrix).

A: Unfortunatelly, seems rgeos and gDistance can't do it... So I found solution using the sf library:
require(sf)
g1 <- st_as_sf(A)
g2 <- st_as_sf(B)
dist <- st_distance(g1, g2, by_element=TRUE)

This is going to generate pairwise distances.


text:
Q: Importing text file into Matlab, dimension not maintained I am trying to upload a text file into matlab as a matrix and then process based on user input so selected data are selected.
These are the first few rows of the data.
The United States of America, Deaths (1x1)     Last modified: 16-Nov-2012, MPv5 (May07)

Year     Age        Female             Male            Total
1933      0          52615.77         68438.11        121053.88
1933      1           8917.13         10329.16         19246.29
1933      2           4336.92          5140.05          9476.97
1933      3           3161.59          3759.88          6921.47
1933      4           2493.84          2932.59          5426.43
1933      5           2139.87          2537.53          4677.40
1933      6           1939.70          2337.76          4277.46
1933      7           1760.47          2163.90          3924.37
1933      8           1602.20          2015.97          3618.17
1933      9           1464.88          1893.96          3358.84

A larger part of the data is present here: https://www.dropbox.com/s/b4njypwmrxwxzl7/USA.Deaths_1x1.txt?dl=0
The problem I am facing is that everytime I use T=readable() to read in the data, the dimension of T is m x 1 table, rather than a m x 5 table.
I also tried to change the txt file into a csv file, but the data has non-numeric entries.
What could I do to accomplish this problem?
Thanks.

A: For your format of data, most straight forward import functions (importdata, dlmread, etc ...) will fail.
textscan has a few parameters which will allow you to import the full file without breaking at the first irregular line, however a few faulty lines will contain NaN.
%// Define special values which can be encoutered
specialValues = {'110+','other_special_values'} ;
formatSpec = '%n%n%f%f%f' ;

%// Read the file, treating special values
fileID = fopen('USA.Deaths_1x1.txt');
C = textscan(fileID, formatSpec, ...
    'delimiter'     , ' ', ...
    'headerlines'   ,3, ...
    'treatAsEmpty'  , specialValues, ...
    'MultipleDelimsAsOne',1 );

fclose(fileID);

%// Convert cell array to matrix
data = cell2mat(C) ;

If you really need the faulty lines data, you'll have to write a more custom parser with the low level function fscanf and account for every edge case (unconventionnal line) that you may encounter.