Better alternatives to join() method have been evolved over a period of time.
ExecutorService.html#invokeAll is one alternative.
Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list.
Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.
ForkJoinPool or Executors.html#newWorkStealingPool provides other alternatives to achieve the same purpose.
Example code snippet:
import java.util.concurrent.*;
import java.util.*;
public class InvokeAllDemo{
public InvokeAllDemo(){
System.out.println("creating service");
ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
List<MyCallable> futureList = new ArrayList<MyCallable>();
for ( int i=0; i<10; i++){
MyCallable myCallable = new MyCallable((long)i);
futureList.add(myCallable);
}
System.out.println("Start");
try{
List<Future<Long>> futures = service.invokeAll(futureList);
}catch(Exception err){
err.printStackTrace();
}
System.out.println("Completed");
service.shutdown();
}
public static void main(String args[]){
InvokeAllDemo demo = new InvokeAllDemo();
}
class MyCallable implements Callable<Long>{
Long id = 0L;
public MyCallable(Long val){
this.id = val;
}
public Long call(){
// Add your business logic
return id;
}
}
}
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
This might not be what you're looking for, but here's something I did for an assignment:
$" = ", ";
print "@ArrayName\n";
I had the same problem and solved it by using the default woocommerce hook to display the product image.
while ( $loop->have_posts() ) : $loop->the_post();
echo woocommerce_get_product_thumbnail('woocommerce_full_size');
endwhile;
Available parameters:
You need to use "\n"
not '\n'
in your gsub. The different quote marks behave differently.
Double quotes "
allow character expansion and expression interpolation ie. they let you use escaped control chars like \n
to represent their true value, in this case, newline, and allow the use of #{expression}
so you can weave variables and, well, pretty much any ruby expression you like into the text.
While on the other hand, single quotes '
treat the string literally, so there's no expansion, replacement, interpolation or what have you.
In this particular case, it's better to use either the .delete
or .tr
String method to delete the newlines.
No there isn't. You can specify a background image but that's not the same thing.
Just to complement the answer given by Thibaut Barrère.
I used
wget -r -nH --cut-dirs=5 -nc ftp://user:pass@server//absolute/path/to/directory
Note the double slash after the server name. If you don't put an extra slash the path is relative to the home directory of user.
-nH
avoids the creation of a directory named after the server name-nc
avoids creating a new file if it already exists on the destination (it is just skipped)--cut-dirs=5
allows to take the content of /absolute/path/to/directory and to put it in the directory where you launch wget. The number 5 is used to filter out the 5 components of the path. The double slash means an extra component.C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
Similar situation for following configuration:
My solution:
JFrame
is the window; it can have one or more JPanel
instances inside it. JPanel
is not the window.
You need a Swing tutorial:
I ran into the issue where the class of 'selected' wasn't being added to my menu item. Turns out that you can't have a NavigateUrl on it for whatever reason.
Once I removed the NavigateUrl it applied the 'selected' css class to the a tag and I was able to apply the background style with:
div.menu ul li a.static.selected
{
background-color: #bfcbd6 !important;
color: #465c71 !important;
text-decoration: none !important;
}
None of the above, if you are on a Mac. Use Charles Proxy. It's the best network/request information collecter that I have ever come across. You can view and edit all outgoing requests, and see the responses from those requests in several forms, depending on the type of the response. It costs 50 dollars for a license, but you can download the trial version and see what you think.
If your on Windows, then I would just stay with Fiddler.
You could modify the query. If you are using SQL Server at the back, you can use Select top n
query for such need. The current implements fetch the whole data from database. Selecting only the required number of rows will give you a performance boost as well.
sed -n '16224,16482p;16483q' filename > newfile
From the sed manual:
p - Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option.
n - If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If there is no more input then sed exits without processing any more commands.
q - Exit
sed
without processing any more commands or input. Note that the current pattern space is printed if auto-print is not disabled with the -n option.
Addresses in a sed script can be in any of the following forms:
number Specifying a line number will match only that line in the input.
An address range can be specified by specifying two addresses separated by a comma (,). An address range matches lines starting from where the first address matches, and continues until the second address matches (inclusively).
You do NOT use double to represent money. Not ever. Use java.math.BigDecimal
instead.
Then you can specify how exactly to do rounding (which is sometimes dictated by law in financial applications!) and don't have to do stupid hacks like this epsilon thing.
Seriously, using floating point types to represent money is extremely unprofessional.
package com.app.relativejavawindow;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.text.TextUtils.TruncateAt;
import android.view.Menu;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final RelativeLayout relativeLayout = new RelativeLayout(this);
final RelativeLayout relativeLayoutbotombar = new RelativeLayout(this);
textView = new TextView(this);
textView.setId(1);
RelativeLayout.LayoutParams relativlayparamter = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
RelativeLayout.LayoutParams relativlaybottombar = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
relativeLayoutbotombar.setLayoutParams(relativlaybottombar);
textView.setText("Simple application that shows how to use marquee, with a long ");
textView.setEllipsize(TruncateAt.MARQUEE);
textView.setSelected(true);
textView.setSingleLine(true);
relativeLayout.addView(relativeLayoutbotombar);
relativeLayoutbotombar.addView(textView);
//relativeLayoutbotombar.setBackgroundColor(Color.BLACK);
setContentView(relativeLayout, relativlayparamter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
this code work properly but if ur screen size is not fill this text it will not move try to palcing white space end of text
I created a global define with more information:
#include <iostream>
#include <ctime>
#include <iomanip>
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) // only show filename and not it's path (less clutter)
#define INFO std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [INFO] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
#define ERROR std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [ERROR] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
static std::time_t time_now = std::time(nullptr);
Use it like this:
INFO << "Hello world" << std::endl;
ERROR << "Goodbye world" << std::endl;
Sample output:
16-06-23 21:33:19 [INFO] main.cpp(main:6) >> Hello world
16-06-23 21:33:19 [ERROR] main.cpp(main:7) >> Goodbye world
Put these lines in your header file. I find this very useful for debugging, etc.
Answer is to add a having clause:
SELECT [columns]
FROM table t1
WHERE value= (select max(value) from table)
AND date = (select MIN(date) from table t2 where t1.value = t2.value)
this should work and gets rid of the neccesity of having an extra sub select in the date clause.
Yes. Try:
class USBDevice : GenericDevice, IOurDevice
Note: The base class should come before the list of interface names.
Of course, you'll still need to implement all the members that the interfaces define. However, if the base class contains a member that matches an interface member, the base class member can work as the implementation of the interface member and you are not required to manually implement it again.
There is a UDF that will do that described here:
User Defined Function to Strip HTML
CREATE FUNCTION [dbo].[udf_StripHTML] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE @Start INT
DECLARE @End INT
DECLARE @Length INT
SET @Start = CHARINDEX('<',@HTMLText)
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
WHILE @Start > 0 AND @End > 0 AND @Length > 0
BEGIN
SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
SET @Start = CHARINDEX('<',@HTMLText)
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
END
RETURN LTRIM(RTRIM(@HTMLText))
END
GO
Edit: note this is for SQL Server 2005, but if you change the keyword MAX to something like 4000, it will work in SQL Server 2000 as well.
UPDATE: I have created a video on sending multipart/form-data requests to explain this better.
Actually, Postman can do this. Here is a screenshot
Newer version : Screenshot captured from postman chrome extension
Another version
Older version
Make sure you check the comment from @maxkoryukov
Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.
https://www.npmjs.com/package/express-list-endpoints works pretty well.
Example
Usage:
const all_routes = require('express-list-endpoints');
console.log(all_routes(app));
Output:
[ { path: '*', methods: [ 'OPTIONS' ] },
{ path: '/', methods: [ 'GET' ] },
{ path: '/sessions', methods: [ 'POST' ] },
{ path: '/sessions', methods: [ 'DELETE' ] },
{ path: '/users', methods: [ 'GET' ] },
{ path: '/users', methods: [ 'POST' ] } ]
According to new Gradle based build system
. We have to put assets
under main
folder.
Or simply right click on your project and create it like
File > New > folder > assets Folder
I wanted to add a warning because I noticed that some of the simple solutions omit the InvokeRequired
check.
I noticed that if your code executes before the window handle of the control has been created (e.g. before the form is shown), Invoke
throws an exception. So I recommend always checking on InvokeRequired
before calling Invoke
or BeginInvoke
.
if the map is short you can do:
ImmutableMap.of(key, value, key2, value2); // ...up to five k-v pairs
If it is longer then:
ImmutableMap.builder()
.put(key, value)
.put(key2, value2)
// ...
.build();
In [7]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
...: dic = {k: v for k, v in dic.items() if v is not None}
1000000 loops, best of 7: 375 ns per loop
In [8]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
...: dic = dict((k, v) for k, v in dic.items() if v is not None)
1000000 loops, best of 7: 681 ns per loop
In [10]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
...: for k, v in dic.items():
...: if v is None:
...: del dic[k]
...:
10000000 loops, best of 7: 160 ns per loop
so loop and delete is the fastest at 160ns, list comprehension is half as slow at ~375ns and with a call to dict()
is half as slow again ~680ns.
Wrapping 3 into a function brings it back down again to about 275ns. Also for me PyPy was about twice as fast as neet python.
A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.
I would say you have two options:
to get all parent divs styled with 100%
height (including body and html)
to use absolute positioning for one of the parent divs (for example #content
) and then all child divs set to height 100%
I found it in this location:
C:\Users\amitsinha02\AppData\Local\Android\sdk\platform-tools
Wasted a few hours trying some of these solutions but eventually traced this to a corporate IPS (Instrusion Protection System) dropping the connection after a certain amount of data is transferred.
There is some faster way (https://www.youtube.com/watch?v=TSjEMLBAYVc):
A caveat which the other answers don't seem to mention is that the time which is shown by dmesg
doesn't take into account any sleep/suspend time. So there are cases where the usual answer of using dmesg -T
doesn't work, and shows a completely wrong time.
A workaround for such situations is to write something to the kernel log at a known time and then use that entry as a reference to calculate the other times. Obviously, it will only work for times after the last suspend.
So to display the correct time for recent entries on machines which may have been suspended since their last boot, use something like this from my other answer here:
# write current time to kernel ring buffer so it appears in dmesg output
echo "timecheck: $(date +%s) = $(date +%F_%T)" | sudo tee /dev/kmsg
# use our "timecheck" entry to get the difference
# between the dmesg timestamp and real time
offset=$(dmesg | grep timecheck | tail -1 \
| perl -nle '($t1,$t2)=/^.(\d+)\S+ timecheck: (\d+)/; print $t2-$t1')
# pipe dmesg output through a Perl snippet to
# convert it's timestamp to correct readable times
dmesg | tail \
| perl -pe 'BEGIN{$offset=shift} s/^\[(\d+)\S+/localtime($1+$offset)/e' $offset
Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
Simple example
Shamelessly adapted from: http://www.gnu.org/software/automake/manual/html_node/Creating-amhello.html and tested on Ubuntu 14.04 Automake 1.14.1.
Makefile.am
SUBDIRS = src
dist_doc_DATA = README.md
README.md
Some doc.
configure.ac
AC_INIT([automake_hello_world], [1.0], [[email protected]])
AM_INIT_AUTOMAKE([-Wall -Werror foreign])
AC_PROG_CC
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_FILES([
Makefile
src/Makefile
])
AC_OUTPUT
src/Makefile.am
bin_PROGRAMS = autotools_hello_world
autotools_hello_world_SOURCES = main.c
src/main.c
#include <config.h>
#include <stdio.h>
int main (void) {
puts ("Hello world from " PACKAGE_STRING);
return 0;
}
Usage
autoreconf --install
mkdir build
cd build
../configure
make
sudo make install
autoconf_hello_world
sudo make uninstall
This outputs:
Hello world from automake_hello_world 1.0
Notes
autoreconf --install
generates several template files which should be tracked by Git, including Makefile.in
. It only needs to be run the first time.
make install
installs:
/usr/local/bin
README.md
to /usr/local/share/doc/automake_hello_world
On GitHub for you to try it out.
You can sort the dataFrame by count and then remove duplicates. I think it's easier:
df.sort_values('count', ascending=False).drop_duplicates(['Sp','Mt'])
Use multiselect function as below.
$('#drp_Books_Ill_Illustrations').multiSelect('select', 'value');
You can get country from IP address with this location API
Code
echo file_get_contents('https://ipapi.co/8.8.8.8/country/');
Response
US
Here's a fiddle. Response is text
when you query a specific field e.g. country
here. No decoding needed, just plug it into your code.
P.S. If you want all the fields e.g. https://ipapi.co/8.8.8.8/json/
, the response is JSON
.
PowerShell is pretty common these days so I use it often as a quick way to invoke C# since that has functions for pretty much everything:
@echo off
set pathToResolve=%~dp0\..\SomeFile.txt
for /f "delims=" %%a in ('powershell -Command "[System.IO.Path]::GetFullPath( '%projectDirMc%' )"') do @set resolvedPath=%%a
echo Resolved path: %resolvedPath%
It's a bit slow, but the functionality gained is hard to beat unless without resorting to an actual scripting language.
If you have Linux machine just install puttygen in your system and use use below command to convert the key
pem to ppk use below command:
puttygen keyname -o keyname.ppk
Below command is use to convert ppk to pem not pem to ppk
puttygen filename.ppk -O private-openssh -o filename.pem
just set the hidden field with javascript :
document.getElementById('elementId').value = 'whatever';
or do I miss something?
Your part:
$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name
Error: " . mysql_error());
mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database
";
Doesn't make much sense, your connection shouldn't be named $result but that is a naming issue not a coding one.
What is a coding issue is if($result), your saying if you can connect to the database regardless of the insert query failing or succeeding you will output "Image saved into database".
Try adding do
$realresult = mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
and change the if($result) to $realresult
I suspect your query is failing, perhaps you have additional columns or something?
Try copy/pasting your query, replacing the ".$_FILES['filep']['name']." with test and running it in your query browser and see if it goes in.
Here is a great tool to decompile pyc files.
It was coded by me and supports python 1.0 - 3.3
Its based on uncompyle2 and decompyle++
For some reason, import as suggested by Ricardo didnt work for me. I got it working with following statement:
<import resource="classpath*:/spring-config.xml" />
Here is an example to convert high res image into thumbnail size-
protected void Button1_Click(object sender, EventArgs e)
{
//---------- Getting the Image File
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/profile/Avatar.jpg"));
//---------- Getting Size of Original Image
double imgHeight = img.Size.Height;
double imgWidth = img.Size.Width;
//---------- Getting Decreased Size
double x = imgWidth / 200;
int newWidth = Convert.ToInt32(imgWidth / x);
int newHeight = Convert.ToInt32(imgHeight / x);
//---------- Creating Small Image
System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
System.Drawing.Image myThumbnail = img.GetThumbnailImage(newWidth, newHeight, myCallback, IntPtr.Zero);
//---------- Saving Image
myThumbnail.Save(Server.MapPath("~/profile/NewImage.jpg"));
}
public bool ThumbnailCallback()
{
return false;
}
Source- http://iknowledgeboy.blogspot.in/2014/03/c-creating-thumbnail-of-large-image-by.html
How about something like:
<a href="\\DangerServer\Downloads\MyVirusArchive.exe"
type="application/octet-stream">Don't download this file!</a>
navigator.sayswho= (function(){_x000D_
var ua= navigator.userAgent, tem, _x000D_
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];_x000D_
if(/trident/i.test(M[1])){_x000D_
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];_x000D_
return 'IE '+(tem[1] || '');_x000D_
}_x000D_
if(M[1]=== 'Chrome'){_x000D_
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);_x000D_
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');_x000D_
}_x000D_
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];_x000D_
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);_x000D_
return M.join(' ');_x000D_
})();_x000D_
_x000D_
console.log(navigator.sayswho); // outputs: `Chrome 62`
_x000D_
I have resolved it by adding below line in my context:
modelBuilder.Entity<YourObject>().Property(e => e.YourColumn).HasMaxLength(4000);
Somehow, [MaxLength]
didn't work for me.
In a command prompt you tell Cmd to use Windows Explorer's command line by prefacing it with start
.
So start Yourbatchname
.
Note you have to register as if its name is batchfile.exe
.
Programs and documents can be added to the registry so typing their name without their path in the Start - Run dialog box or shortcut enables Windows to find them.
This is a generic reg file. Copy the lines below to a new Text Document and save it as anyname.reg. Edit it with your programs or documents.
In paths, use \\
to separate folder names in key paths as regedit uses a single \
to separate its key names. All reg files start with REGEDIT4. A semicolon turns a line into a comment. The @
symbol means to assign the value to the key rather than a named value.
The file doesn't have to exist. This can be used to set Word.exe to open Winword.exe.
Typing start batchfile
will start iexplore.exe.
REGEDIT4
;The bolded name below is the name of the document or program, <filename>.<file extension>
[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\Batchfile.exe]
; The @ means the path to the file is assigned to the default value for the key.
; The whole path in enclosed in a quotation mark ".
@="\"C:\\Program Files\\Internet Explorer\\iexplore.exe\""
; Optional Parameters. The semicolon means don't process the line. Remove it if you want to put it in the registry
; Informs the shell that the program accepts URLs.
;"useURL"="1"
; Sets the path that a program will use as its' default directory. This is commented out.
;"Path"="C:\\Program Files\\Microsoft Office\\Office\\"
You've already been told about path in another answer. Also see doskey /?
for cmd macros (they only work when typing).
You can run startup commands for CMD. From Windows Resource Kit Technical Reference
AutoRun
HKCU\Software\Microsoft\Command Processor
Data type Range Default value
REG_SZ list of commands There is no default value for this entry.
Description
Contains commands which are executed each time you start Cmd.exe.
if you are using html agility pack use getattributeValue:
$doc2.DocumentNode.SelectNodes("//div[@class='className']/div[@class='InternalClass']/a[@class='InternalClass']").GetAttributeValue("href","")
I had a similar issue. It is caused due the dependent package 'rJava'. This problem can be overcome by re-directing the R to use a different JAVA_HOME
.
if(Sys.getenv("JAVA_HOME")!=""){
Sys.setenv(JAVA_HOME="")
}
library(rJava)
This worked for me.
A bit late, but to anyone who is wondering why they are getting the "Warning: Cannot use a scalar value as an array" message;
the reason is because somewhere you have first declared your variable with a normal integer or string and then later you are trying to turn it into an array.
hope that helps
Take a look at Array.slice(begin, end)
const ar = [1, 2, 3, 4, 5];
// slice from 1..3 - add 1 as the end index is not included
const ar2 = ar.slice(1, 3 + 1);
console.log(ar2);
_x000D_
It is indeed possible with the following code
<div href="#" id='a'>
Hover me
</div>
<div id='b'>
Show me
</div>
and css
#a {
display: block;
}
#a:hover + #b {
display:block;
}
#b {
display:none;
}
Now by hovering on element #a shows element #b.
The access token is returned as a URI fragment after you authorize the application to use your Instagram data. It should look something like the following:
let canvas = document.getElementById('canvas');_x000D_
canvas.setAttribute('width', window.innerWidth);_x000D_
canvas.setAttribute('height', window.innerHeight);_x000D_
let ctx = canvas.getContext('2d');_x000D_
_x000D_
//Draw Canvas Fill mode_x000D_
ctx.fillStyle = 'blue';_x000D_
ctx.fillRect(0,0,canvas.width, canvas.height);
_x000D_
* { margin: 0; padding: 0; box-sizing: border-box; }_x000D_
body { overflow: hidden; }
_x000D_
<canvas id='canvas'></canvas>
_x000D_
A simple query that shows only whether you are a SysAdmin or not :
IF IS_SRVROLEMEMBER ('sysadmin') = 1
print 'Current user''s login is a member of the sysadmin role'
ELSE IF IS_SRVROLEMEMBER ('sysadmin') = 0
print 'Current user''s login is NOT a member of the sysadmin role'
ELSE IF IS_SRVROLEMEMBER ('sysadmin') IS NULL
print 'ERROR: The server role specified is not valid.';
I have a cook recipe for finding things in linux/macos
First update the locate db then do a
locate WHATiWANTtoSEARCH | less
do a /find to find what you are looking for.
to update your locate db in macos do this:
sudo /usr/libexec/locate.updatedb
it sometimes takes a while. Hope this helps :)
@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0
For SQL Server 2012:
SELECT name, modify_date, create_date, type
FROM sys.procedures
WHERE name like '%XXX%'
ORDER BY modify_date desc
Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure
show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.
Mallocs and frees need to be paired up.
malloc grabbed a chunk of memory big enough for Person.
When you free you tell malloc the piece of memory starting "here" is no longer needed, it knows how much it allocated and frees it.
Whether you call
free(testPerson)
or
free(testPerson->firstName)
all that free() actually receives is an address, the same address, it can't tell which you called. Your code is much clearer if you use free(testPerson) though - it clearly matches up the with malloc.
There is an in-built stopword list in NLTK
made up of 2,400 stopwords for 11 languages (Porter et al), see http://nltk.org/book/ch02.html
>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> stop = set(stopwords.words('english'))
>>> sentence = "this is a foo bar sentence"
>>> print([i for i in sentence.lower().split() if i not in stop])
['foo', 'bar', 'sentence']
>>> [i for i in word_tokenize(sentence.lower()) if i not in stop]
['foo', 'bar', 'sentence']
I recommend looking at using tf-idf to remove stopwords, see Effects of Stemming on the term frequency?
Instead of putting the listview inside Scrollview, put the rest of the content between listview and the opening of the Scrollview as a separate view and set that view as the header of the listview. So you will finally end up only list view taking charge of Scroll.
Eclipse for PHP Developers Package
Looking for the Eclipse for PHP Developers Package?
Due to lack of a package maintainer for the Indigo release there will be no PHP (PDT) package. If you would like to install PDT into your Eclipse installtion you can do so by using the Install New Software feature from the Help Menu and installing the PHP Development Tools (PDT) SDK Feature from the Eclipse Indigo Repo >> http://download.eclipse.org/releases/indigo
Text grabbed from page: http://www.eclipse.org/downloads/php_package.php
The following answer could be helpful for the first part of your question:
New introduction 2
In the previous version of macro "SaveEmailDetails" I used this statement to find Inbox:
Set FolderTgt = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
I have since installed a newer version of Outlook and I have discovered that it does not use the default Inbox. For each of my email accounts, it created a separate store (named for the email address) each with its own Inbox. None of those Inboxes is the default.
This macro, outputs the name of the store holding the default Inbox to the Immediate Window:
Sub DsplUsernameOfDefaultStore()
Dim NS As Outlook.NameSpace
Dim DefaultInboxFldr As MAPIFolder
Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
Set DefaultInboxFldr = NS.GetDefaultFolder(olFolderInbox)
Debug.Print DefaultInboxFldr.Parent.Name
End Sub
On my installation, this outputs: "Outlook Data File".
I have added an extra statement to macro "SaveEmailDetails" that shows how to access the Inbox of any store.
New introduction 1
A number of people have picked up the macro below, found it useful and have contacted me directly for further advice. Following these contacts I have made a few improvements to the macro so I have posted the revised version below. I have also added a pair of macros which together will return the MAPIFolder object for any folder with the Outlook hierarchy. These are useful if you wish to access other than a default folder.
The original text referenced one question by date which linked to an earlier question. The first question has been deleted so the link has been lost. That link was to Update excel sheet based on outlook mail (closed)
Original text
There are a surprising number of variations of the question: "How do I extract data from Outlook emails to Excel workbooks?" For example, two questions up on [outlook-vba] the same question was asked on 13 August. That question references a variation from December that I attempted to answer.
For the December question, I went overboard with a two part answer. The first part was a series of teaching macros that explored the Outlook folder structure and wrote data to text files or Excel workbooks. The second part discussed how to design the extraction process. For this question Siddarth has provided an excellent, succinct answer and then a follow-up to help with the next stage.
What the questioner of every variation appears unable to understand is that showing us what the data looks like on the screen does not tell us what the text or html body looks like. This answer is an attempt to get past that problem.
The macro below is more complicated than Siddarth’s but a lot simpler that those I included in my December answer. There is more that could be added but I think this is enough to start with.
The macro creates a new Excel workbook and outputs selected properties of every email in Inbox to create this worksheet:
Near the top of the macro there is a comment containing eight hashes (#). The statement below that comment must be changed because it identifies the folder in which the Excel workbook will be created.
All other comments containing hashes suggest amendments to adapt the macro to your requirements.
How are the emails from which data is to be extracted identified? Is it the sender, the subject, a string within the body or all of these? The comments provide some help in eliminating uninteresting emails. If I understand the question correctly, an interesting email will have Subject = "Task Completed"
.
The comments provide no help in extracting data from interesting emails but the worksheet shows both the text and html versions of the email body if they are present. My idea is that you can see what the macro will see and start designing the extraction process.
This is not shown in the screen image above but the macro outputs two versions on the text body. The first version is unchanged which means tab, carriage return, line feed are obeyed and any non-break spaces look like spaces. In the second version, I have replaced these codes with the strings [TB], [CR], [LF] and [NBSP] so they are visible. If my understanding is correct, I would expect to see the following within the second text body:
Activity[TAB]Count[CR][LF]Open[TAB]35[CR][LF]HCQA[TAB]42[CR][LF]HCQC[TAB]60[CR][LF]HAbst[TAB]50 45 5 2 2 1[CR][LF] and so on
Extracting the values from the original of this string should not be difficult.
I would try amending my macro to output the extracted values in addition to the email’s properties. Only when I have successfully achieved this change would I attempt to write the extracted data to an existing workbook. I would also move processed emails to a different folder. I have shown where these changes must be made but give no further help. I will respond to a supplementary question if you get to the point where you need this information.
Good luck.
Latest version of macro included within the original text
Option Explicit
Public Sub SaveEmailDetails()
' This macro creates a new Excel workbook and writes to it details
' of every email in the Inbox.
' Lines starting with hashes either MUST be changed before running the
' macro or suggest changes you might consider appropriate.
Dim AttachCount As Long
Dim AttachDtl() As String
Dim ExcelWkBk As Excel.Workbook
Dim FileName As String
Dim FolderTgt As MAPIFolder
Dim HtmlBody As String
Dim InterestingItem As Boolean
Dim InxAttach As Long
Dim InxItemCrnt As Long
Dim PathName As String
Dim ReceivedTime As Date
Dim RowCrnt As Long
Dim SenderEmailAddress As String
Dim SenderName As String
Dim Subject As String
Dim TextBody As String
Dim xlApp As Excel.Application
' The Excel workbook will be created in this folder.
' ######## Replace "C:\DataArea\SO" with the name of a folder on your disc.
PathName = "C:\DataArea\SO"
' This creates a unique filename.
' #### If you use a version of Excel 2003, change the extension to "xls".
FileName = Format(Now(), "yymmdd hhmmss") & ".xlsx"
' Open own copy of Excel
Set xlApp = Application.CreateObject("Excel.Application")
With xlApp
' .Visible = True ' This slows your macro but helps during debugging
.ScreenUpdating = False ' Reduces flash and increases speed
' Create a new workbook
' #### If updating an existing workbook, replace with an
' #### Open workbook statement.
Set ExcelWkBk = xlApp.Workbooks.Add
With ExcelWkBk
' #### None of this code will be useful if you are adding
' #### to an existing workbook. However, it demonstrates a
' #### variety of useful statements.
.Worksheets("Sheet1").Name = "Inbox" ' Rename first worksheet
With .Worksheets("Inbox")
' Create header line
With .Cells(1, "A")
.Value = "Field"
.Font.Bold = True
End With
With .Cells(1, "B")
.Value = "Value"
.Font.Bold = True
End With
.Columns("A").ColumnWidth = 18
.Columns("B").ColumnWidth = 150
End With
End With
RowCrnt = 2
End With
' FolderTgt is the folder I am going to search. This statement says
' I want to seach the Inbox. The value "olFolderInbox" can be replaced
' to allow any of the standard folders to be searched.
' See FindSelectedFolder() for a routine that will search for any folder.
Set FolderTgt = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
' #### Use the following the access a non-default Inbox.
' #### Change "Xxxx" to name of one of your store you want to access.
Set FolderTgt = Session.Folders("Xxxx").Folders("Inbox")
' This examines the emails in reverse order. I will explain why later.
For InxItemCrnt = FolderTgt.Items.Count To 1 Step -1
With FolderTgt.Items.Item(InxItemCrnt)
' A folder can contain several types of item: mail items, meeting items,
' contacts, etc. I am only interested in mail items.
If .Class = olMail Then
' Save selected properties to variables
ReceivedTime = .ReceivedTime
Subject = .Subject
SenderName = .SenderName
SenderEmailAddress = .SenderEmailAddress
TextBody = .Body
HtmlBody = .HtmlBody
AttachCount = .Attachments.Count
If AttachCount > 0 Then
ReDim AttachDtl(1 To 7, 1 To AttachCount)
For InxAttach = 1 To AttachCount
' There are four types of attachment:
' * olByValue 1
' * olByReference 4
' * olEmbeddedItem 5
' * olOLE 6
Select Case .Attachments(InxAttach).Type
Case olByValue
AttachDtl(1, InxAttach) = "Val"
Case olEmbeddeditem
AttachDtl(1, InxAttach) = "Ebd"
Case olByReference
AttachDtl(1, InxAttach) = "Ref"
Case olOLE
AttachDtl(1, InxAttach) = "OLE"
Case Else
AttachDtl(1, InxAttach) = "Unk"
End Select
' Not all types have all properties. This code handles
' those missing properties of which I am aware. However,
' I have never found an attachment of type Reference or OLE.
' Additional code may be required for them.
Select Case .Attachments(InxAttach).Type
Case olEmbeddeditem
AttachDtl(2, InxAttach) = ""
Case Else
AttachDtl(2, InxAttach) = .Attachments(InxAttach).PathName
End Select
AttachDtl(3, InxAttach) = .Attachments(InxAttach).FileName
AttachDtl(4, InxAttach) = .Attachments(InxAttach).DisplayName
AttachDtl(5, InxAttach) = "--"
' I suspect Attachment had a parent property in early versions
' of Outlook. It is missing from Outlook 2016.
On Error Resume Next
AttachDtl(5, InxAttach) = .Attachments(InxAttach).Parent
On Error GoTo 0
AttachDtl(6, InxAttach) = .Attachments(InxAttach).Position
' Class 5 is attachment. I have never seen an attachment with
' a different class and do not see the purpose of this property.
' The code will stop here if a different class is found.
Debug.Assert .Attachments(InxAttach).Class = 5
AttachDtl(7, InxAttach) = .Attachments(InxAttach).Class
Next
End If
InterestingItem = True
Else
InterestingItem = False
End If
End With
' The most used properties of the email have been loaded to variables but
' there are many more properies. Press F2. Scroll down classes until
' you find MailItem. Look through the members and note the name of
' any properties that look useful. Look them up using VB Help.
' #### You need to add code here to eliminate uninteresting items.
' #### For example:
'If SenderEmailAddress <> "[email protected]" Then
' InterestingItem = False
'End If
'If InStr(Subject, "Accounts payable") = 0 Then
' InterestingItem = False
'End If
'If AttachCount = 0 Then
' InterestingItem = False
'End If
' #### If the item is still thought to be interesting I
' #### suggest extracting the required data to variables here.
' #### You should consider moving processed emails to another
' #### folder. The emails are being processed in reverse order
' #### to allow this removal of an email from the Inbox without
' #### effecting the index numbers of unprocessed emails.
If InterestingItem Then
With ExcelWkBk
With .Worksheets("Inbox")
' #### This code creates a dividing row and then
' #### outputs a property per row. Again it demonstrates
' #### statements that are likely to be useful in the final
' #### version
' Create dividing row between emails
.Rows(RowCrnt).RowHeight = 5
.Range(.Cells(RowCrnt, "A"), .Cells(RowCrnt, "B")) _
.Interior.Color = RGB(0, 255, 0)
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Sender name"
.Cells(RowCrnt, "B").Value = SenderName
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Sender email address"
.Cells(RowCrnt, "B").Value = SenderEmailAddress
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Received time"
With .Cells(RowCrnt, "B")
.NumberFormat = "@"
.Value = Format(ReceivedTime, "mmmm d, yyyy h:mm")
End With
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Subject"
.Cells(RowCrnt, "B").Value = Subject
RowCrnt = RowCrnt + 1
If AttachCount > 0 Then
.Cells(RowCrnt, "A").Value = "Attachments"
.Cells(RowCrnt, "B").Value = "Inx|Type|Path name|File name|Display name|Parent|Position|Class"
RowCrnt = RowCrnt + 1
For InxAttach = 1 To AttachCount
.Cells(RowCrnt, "B").Value = InxAttach & "|" & _
AttachDtl(1, InxAttach) & "|" & _
AttachDtl(2, InxAttach) & "|" & _
AttachDtl(3, InxAttach) & "|" & _
AttachDtl(4, InxAttach) & "|" & _
AttachDtl(5, InxAttach) & "|" & _
AttachDtl(6, InxAttach) & "|" & _
AttachDtl(7, InxAttach)
RowCrnt = RowCrnt + 1
Next
End If
If TextBody <> "" Then
' ##### This code was in the original version of the macro
' ##### but I did not find it as useful as the other version of
' ##### the text body. See below
' This outputs the text body with CR, LF and TB obeyed
'With .Cells(RowCrnt, "A")
' .Value = "text body"
' .VerticalAlignment = xlTop
'End With
'With .Cells(RowCrnt, "B")
' ' The maximum size of a cell 32,767
' .Value = Mid(TextBody, 1, 32700)
' .WrapText = True
'End With
'RowCrnt = RowCrnt + 1
' This outputs the text body with NBSP, CR, LF and TB
' replaced by strings.
With .Cells(RowCrnt, "A")
.Value = "text body"
.VerticalAlignment = xlTop
End With
TextBody = Replace(TextBody, Chr(160), "[NBSP]")
TextBody = Replace(TextBody, vbCr, "[CR]")
TextBody = Replace(TextBody, vbLf, "[LF]")
TextBody = Replace(TextBody, vbTab, "[TB]")
With .Cells(RowCrnt, "B")
' The maximum size of a cell 32,767
.Value = Mid(TextBody, 1, 32700)
.WrapText = True
End With
RowCrnt = RowCrnt + 1
End If
If HtmlBody <> "" Then
' ##### This code was in the original version of the macro
' ##### but I did not find it as useful as the other version of
' ##### the html body. See below
' This outputs the html body with CR, LF and TB obeyed
'With .Cells(RowCrnt, "A")
' .Value = "Html body"
' .VerticalAlignment = xlTop
'End With
'With .Cells(RowCrnt, "B")
' .Value = Mid(HtmlBody, 1, 32700)
' .WrapText = True
'End With
'RowCrnt = RowCrnt + 1
' This outputs the html body with NBSP, CR, LF and TB
' replaced by strings.
With .Cells(RowCrnt, "A")
.Value = "Html body"
.VerticalAlignment = xlTop
End With
HtmlBody = Replace(HtmlBody, Chr(160), "[NBSP]")
HtmlBody = Replace(HtmlBody, vbCr, "[CR]")
HtmlBody = Replace(HtmlBody, vbLf, "[LF]")
HtmlBody = Replace(HtmlBody, vbTab, "[TB]")
With .Cells(RowCrnt, "B")
.Value = Mid(HtmlBody, 1, 32700)
.WrapText = True
End With
RowCrnt = RowCrnt + 1
End If
End With
End With
End If
Next
With xlApp
With ExcelWkBk
' Write new workbook to disc
If Right(PathName, 1) <> "\" Then
PathName = PathName & "\"
End If
.SaveAs FileName:=PathName & FileName
.Close
End With
.Quit ' Close our copy of Excel
End With
Set xlApp = Nothing ' Clear reference to Excel
End Sub
Macros not included in original post but which some users of above macro have found useful.
Public Sub FindSelectedFolder(ByRef FolderTgt As MAPIFolder, _
ByVal NameTgt As String, ByVal NameSep As String)
' This routine (and its sub-routine) locate a folder within the hierarchy and
' returns it as an object of type MAPIFolder
' NameTgt The name of the required folder in the format:
' FolderName1 NameSep FolderName2 [ NameSep FolderName3 ] ...
' If NameSep is "|", an example value is "Personal Folders|Inbox"
' FolderName1 must be an outer folder name such as
' "Personal Folders". The outer folder names are typically the names
' of PST files. FolderName2 must be the name of a folder within
' Folder1; in the example "Inbox". FolderName2 is compulsory. This
' routine cannot return a PST file; only a folder within a PST file.
' FolderName3, FolderName4 and so on are optional and allow a folder
' at any depth with the hierarchy to be specified.
' NameSep A character or string used to separate the folder names within
' NameTgt.
' FolderTgt On exit, the required folder. Set to Nothing if not found.
' This routine initialises the search and finds the top level folder.
' FindSelectedSubFolder() is used to find the target folder within the
' top level folder.
Dim InxFolderCrnt As Long
Dim NameChild As String
Dim NameCrnt As String
Dim Pos As Long
Dim TopLvlFolderList As Folders
Set FolderTgt = Nothing ' Target folder not found
Set TopLvlFolderList = _
CreateObject("Outlook.Application").GetNamespace("MAPI").Folders
' Split NameTgt into the name of folder at current level
' and the name of its children
Pos = InStr(NameTgt, NameSep)
If Pos = 0 Then
' I need at least a level 2 name
Exit Sub
End If
NameCrnt = Mid(NameTgt, 1, Pos - 1)
NameChild = Mid(NameTgt, Pos + 1)
' Look for current name. Drop through and return nothing if name not found.
For InxFolderCrnt = 1 To TopLvlFolderList.Count
If NameCrnt = TopLvlFolderList(InxFolderCrnt).Name Then
' Have found current name. Call FindSelectedSubFolder() to
' look for its children
Call FindSelectedSubFolder(TopLvlFolderList.Item(InxFolderCrnt), _
FolderTgt, NameChild, NameSep)
Exit For
End If
Next
End Sub
Public Sub FindSelectedSubFolder(FolderCrnt As MAPIFolder, _
ByRef FolderTgt As MAPIFolder, _
ByVal NameTgt As String, ByVal NameSep As String)
' See FindSelectedFolder() for an introduction to the purpose of this routine.
' This routine finds all folders below the top level
' FolderCrnt The folder to be seached for the target folder.
' NameTgt The NameTgt passed to FindSelectedFolder will be of the form:
' A|B|C|D|E
' A is the name of outer folder which represents a PST file.
' FindSelectedFolder() removes "A|" from NameTgt and calls this
' routine with FolderCrnt set to folder A to search for B.
' When this routine finds B, it calls itself with FolderCrnt set to
' folder B to search for C. Calls are nested to whatever depth are
' necessary.
' NameSep As for FindSelectedSubFolder
' FolderTgt As for FindSelectedSubFolder
Dim InxFolderCrnt As Long
Dim NameChild As String
Dim NameCrnt As String
Dim Pos As Long
' Split NameTgt into the name of folder at current level
' and the name of its children
Pos = InStr(NameTgt, NameSep)
If Pos = 0 Then
NameCrnt = NameTgt
NameChild = ""
Else
NameCrnt = Mid(NameTgt, 1, Pos - 1)
NameChild = Mid(NameTgt, Pos + 1)
End If
' Look for current name. Drop through and return nothing if name not found.
For InxFolderCrnt = 1 To FolderCrnt.Folders.Count
If NameCrnt = FolderCrnt.Folders(InxFolderCrnt).Name Then
' Have found current name.
If NameChild = "" Then
' Have found target folder
Set FolderTgt = FolderCrnt.Folders(InxFolderCrnt)
Else
'Recurse to look for children
Call FindSelectedSubFolder(FolderCrnt.Folders(InxFolderCrnt), _
FolderTgt, NameChild, NameSep)
End If
Exit For
End If
Next
' If NameCrnt not found, FolderTgt will be returned unchanged. Since it is
' initialised to Nothing at the beginning, that will be the returned value.
End Sub
Abstraction delineates a context-specific, simplified representation of something; it ignores contextually-irrelevant details and includes contextually-important details.
Encapsulation restricts outside access to something's parts and bundles that thing's state with the procedures that use the state.
Take people, for instance. In the context of surgery a useful abstraction ignores a person's religious beliefs and includes the person's body. Further, people encapsulate their memories with the thought processes that use those memories. An abstraction need not have encapsulation; for instance, a painting of a person neither hides its parts nor bundles procedures with its state. And, encapsulation need not have an associated abstraction; for instance, real people (not abstract ones) encapsulate their organs with their metabolism.
Andy Hayden mentioned the correct function (to_sql
). In this answer, I'll give a complete example, which I tested with Python 3.5 but should also work for Python 2.7 (and Python 3.x):
First, let's create the dataframe:
# Create dataframe
import pandas as pd
import numpy as np
np.random.seed(0)
number_of_samples = 10
frame = pd.DataFrame({
'feature1': np.random.random(number_of_samples),
'feature2': np.random.random(number_of_samples),
'class': np.random.binomial(2, 0.1, size=number_of_samples),
},columns=['feature1','feature2','class'])
print(frame)
Which gives:
feature1 feature2 class
0 0.548814 0.791725 1
1 0.715189 0.528895 0
2 0.602763 0.568045 0
3 0.544883 0.925597 0
4 0.423655 0.071036 0
5 0.645894 0.087129 0
6 0.437587 0.020218 0
7 0.891773 0.832620 1
8 0.963663 0.778157 0
9 0.383442 0.870012 0
To import this dataframe into a MySQL table:
# Import dataframe into MySQL
import sqlalchemy
database_username = 'ENTER USERNAME'
database_password = 'ENTER USERNAME PASSWORD'
database_ip = 'ENTER DATABASE IP'
database_name = 'ENTER DATABASE NAME'
database_connection = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'.
format(database_username, database_password,
database_ip, database_name))
frame.to_sql(con=database_connection, name='table_name_for_df', if_exists='replace')
One trick is that MySQLdb doesn't work with Python 3.x. So instead we use mysqlconnector
, which may be installed as follows:
pip install mysql-connector==2.1.4 # version avoids Protobuf error
Output:
Note that to_sql
creates the table as well as the columns if they do not already exist in the database.
To resolve your problem, write the following line on your page's Page_Load method.
if (String.IsNullOrEmpty(Request.QueryString["aspxerrorpath"])) return;
.Net 4.0 provides more closer look to null, empty or whitespace strings, use it as shown in the following line:
if(string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"])) return;
This will not run your next statements (your business logics) if query string does not have aspxerrorpath.
Best Firefox Addon to disable CORS as of September 2016: https://github.com/fredericlb/Force-CORS/releases
You can even configure it by Referrers (Website).
You may want to look into jQuery UI. Specifically, the highlight effect:
Number of TCP connections will help you. Remember that it is not for a particular database
netstat -a -n | find /c "127.0.0.1:13306"
I had a similar problem, however in my case I could pull/push to the remote branch but git status
didn't show the local branch state w.r.t the remote ones.
Also, in my case git config --get remote.origin.fetch
didn't return anything
The problem is that there was a typo in the .git/config
file in the fetch line of the respective remote block. Probably something I added by mistake previously (sometimes I directly look at this file, or even edit it)
So, check if your remote entry in the .git/config
file is correct, e.g.:
[remote "origin"]
url = https://[server]/[user or organization]/[repo].git
fetch = +refs/heads/*:refs/remotes/origin/*
Should it be necessary to manually remove a service:
You will have to reboot before the list gets updated in services
As shown in this example, you can apply a background to a canvas
element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL()
.
Here are the contents of the example, for Stack Overflow posterity:
<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8">
<title>Canvas Background through CSS</title>
<style type="text/css" media="screen">
canvas, img { display:block; margin:1em auto; border:1px solid black; }
canvas { background:url(lotsalasers.jpg) }
</style>
</head><body>
<canvas width="800" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
var can = document.getElementsByTagName('canvas')[0];
var ctx = can.getContext('2d');
ctx.strokeStyle = '#f00';
ctx.lineWidth = 6;
ctx.lineJoin = 'round';
ctx.strokeRect(140,60,40,40);
var img = document.getElementsByTagName('img')[0];
img.src = can.toDataURL();
</script>
</body></html>
@JAB's answer is fast and concise. But it changes the DataFrame
you are trying to sort, which you may or may not want.
(Note: You almost certainly will want it, because your date columns should be dates, not strings!)
In the unlikely event that you don't want to change the dates into dates, you can also do it a different way.
First, get the index from your sorted Date
column:
In [25]: pd.to_datetime(df.Date).order().index
Out[25]: Int64Index([0, 2, 1], dtype='int64')
Then use it to index your original DataFrame
, leaving it untouched:
In [26]: df.ix[pd.to_datetime(df.Date).order().index]
Out[26]:
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
Magic!
Note: for Pandas versions 0.20.0 and later, use loc
instead of ix
, which is now deprecated.
You can always use Sharepoint Solution Generator to create a project and edit in VS2008.
You can find the Generator along with Sharepoint Developer tools.
Convert String to Int in Swift 2.0:
var str:NSString = Data as! NSString
var cont:Int = str.integerValue
use .intergerValue or intValue for Int32
string result = Encoding.UTF8.GetString((stream as MemoryStream).ToArray());
i have tried following solution and it had work for me C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe right click on Devenv.exe in Compablity tab --> Privilage Level --> click on Run this Program as an Adminstrator If as for the Admin Password Provide it
if it is already selected deselect it and again select it -->Apply-->OK
restart the VS application and Publish your website again
As vim's own help on set background
says, "Setting this option does not change the background color, it tells Vim what the background color looks like. For changing the background color, see |:hi-normal|."
For example
:highlight Normal ctermfg=grey ctermbg=darkblue
will write in white on blue on your color terminal.
$("#dropdownList option[text='it\'s me']").attr("selected","selected");
if cordova app copy a valid png file to
resources\android\icon.png
and then run
ionic resources --icon
Removed NOT operation in alpha-numeric validation. Moved variables to block level scope. Some comments here and there. Derived from the best Micheal
function isAlphaNumeric ( str ) {
/* Iterating character by character to get ASCII code for each character */
for ( let i = 0, len = str.length, code = 0; i < len; ++i ) {
/* Collecting charCode from i index value in a string */
code = str.charCodeAt( i );
/* Validating charCode falls into anyone category */
if (
( code > 47 && code < 58) // numeric (0-9)
|| ( code > 64 && code < 91) // upper alpha (A-Z)
|| ( code > 96 && code < 123 ) // lower alpha (a-z)
) {
continue;
}
/* If nothing satisfies then returning false */
return false
}
/* After validating all the characters and we returning success message*/
return true;
};
console.log(isAlphaNumeric("oye"));
console.log(isAlphaNumeric("oye123"));
console.log(isAlphaNumeric("oye%123"));
_x000D_
This method does not need to modify dtype or ravel your numpy array.
The core idea is: 1.initialize with one extra row. 2.change the list(which has one more row) to array 3.delete the extra row in the result array e.g.
>>> a = [np.zeros((10,224)), np.zeros((10,))]
>>> np.array(a)
# this will raise error,
ValueError: could not broadcast input array from shape (10,224) into shape (10)
# but below method works
>>> a = [np.zeros((11,224)), np.zeros((10,))]
>>> b = np.array(a)
>>> b[0] = np.delete(b[0],0,0)
>>> print(b.shape,b[0].shape,b[1].shape)
# print result:(2,) (10,224) (10,)
Indeed, it's not necessarily to add one more row, as long as you can escape from the gap stated in @aravk33 and @user707650 's answer and delete the extra item later, it will be fine.
Try an OUTER APPLY
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
OUTER APPLY
(
SELECT TOP 1 *
FROM tbl_Media M
WHERE M.Content_Id = C.Content_Id
) m
ORDER BY
C.Content_DatePublished ASC
Alternatively, you could GROUP BY
the results
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id
GROUP BY
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
ORDER BY
C.Content_DatePublished ASC
The OUTER APPLY
selects a single row (or none) that matches each row from the left table.
The GROUP BY
performs the entire join, but then collapses the final result rows on the provided columns.
simply using Viewbag data as IEnumerable<> list
@{
var getlist= ViewBag.Listdata as IEnumerable<myproject.models.listmodel>;
foreach (var item in getlist){ //using foreach
<span>item .name</span>
}
}
//---------or just write name inside the getlist
<span>getlist[0].name</span>
I imagine a lot of data comes into Pandas from CSV files, in which case you can simply convert the date during the initial CSV read:
dfcsv = pd.read_csv('xyz.csv', parse_dates=[0])
where the 0 refers to the column the date is in.
You could also add , index_col=0
in there if you want the date to be your index.
See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
The practical answer seems to be one that considers the context:
1) Public site (no login)
Code the UI to work with both options together.
2) Login site
Capture whether a mouse-move occurred on the login form, and save this into a hidden input. The value is passed with the login credentials and added to the user's session, so it can be used for the duration of the session.
Jquery to add to login page only:
$('#istouch').val(1); // <-- value will be submitted with login form
if (window.addEventListener) {
window.addEventListener('mousemove', function mouseMoveListener(){
// Update hidden input value to false, and stop listening
$('#istouch').val(0);
window.removeEventListener('mousemove', mouseMoveListener);
});
}
(+1 to @Dave Burt and +1 to @Martin Lantzsch on their answers)
In order to forcefully let the namenode leave safemode, following command should be executed:
bin/hadoop dfsadmin -safemode leave
You are getting Unknown command
error for your command as -safemode
isn't a sub-command for hadoop fs
, but it is of hadoop dfsadmin
.
Also after the above command, I would suggest you to once run hadoop fsck
so that any inconsistencies crept in the hdfs might be sorted out.
Update:
Use hdfs
command instead of hadoop
command for newer distributions. The hadoop
command is being deprecated:
hdfs dfsadmin -safemode leave
hadoop dfsadmin
has been deprecated and so is hadoop fs
command, all hdfs related tasks are being moved to a separate command hdfs
.
This should work and protect your form from being submitted if the number of files is greater then max_file_number.
$(function() {
var // Define maximum number of files.
max_file_number = 3,
// Define your form id or class or just tag.
$form = $('form'),
// Define your upload field class or id or tag.
$file_upload = $('#image_upload', $form),
// Define your submit class or id or tag.
$button = $('.submit', $form);
// Disable submit button on page ready.
$button.prop('disabled', 'disabled');
$file_upload.on('change', function () {
var number_of_images = $(this)[0].files.length;
if (number_of_images > max_file_number) {
alert(`You can upload maximum ${max_file_number} files.`);
$(this).val('');
$button.prop('disabled', 'disabled');
} else {
$button.prop('disabled', false);
}
});
});
Here is what the JSF javadocs have to say about the commandButton
action
attribute:
MethodExpression representing the application action to invoke when this component is activated by the user. The expression must evaluate to a public method that takes no parameters, and returns an Object (the toString() of which is called to derive the logical outcome) which is passed to the NavigationHandler for this application.
It would be illuminating to me if anyone can explain what that has to do with any of the answers on this page. It seems pretty clear that action
refers to some page's filename and not a method.
if you want page numbering:
Example: 1 2 3 4...
HTML:
<div class="slider">
<div>
<div>Some content</div>
<div class="slider-number"><span>1 2 3 4...</span></div>
</div>
<div>
<div>Some content</div>
<div class="slider-number"><span>1 2 3 4...</span></div>
</div>
...
...
</div>
JS:
$('.slider').on('init reInit afterChange',
function(event, slick, currentSlide){
var status = $(this).find('.slider-number span');
//currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
var i = slick.currentSlide;
var slidesLength = slick.slideCount;
var numberSlide1 = i + 1 <= slidesLength ? i + 1 : i - (slidesLength - 1);
var numberSlide2 = i + 2 <= slidesLength ? i + 2 : i - (slidesLength - 2);
var numberSlide3 = i + 3 <= slidesLength ? i + 3 : i - (slidesLength - 3);
var numberSlide4 = i + 4 <= slidesLength ? i + 4 : i - (slidesLength - 4);
status.html('<strong>'+numberSlide1+'</strong>' + ' ' +
numberSlide2 + ' ' +
numberSlide3 + ' ' +
numberSlide4 + '...');
});
The accepted answer don't work well for negative numbers between -0 and -1.0 Also give the fractional part negative.
For example: For number -0,35
returns
Integer part = 0 Fractional part = -0.35
If wou are working with GPS coordinates it is better to have a result with the signum on the integer part as:
Integer part = -0 Fractional part = 0.35
Theses numbers are used for example for GPS coordinates, where are important the signum for Lat or Long position
Propose code:
double num;
double iPart;
double fPart;
// Get user input
num = -0.35d;
iPart = (long) num;
//Correct numbers between -0.0 and -1.0
iPart = (num<=-0.0000001 && num>-1.0)? -iPart : iPart ;
fPart = Math.abs(num - iPart);
System.out.println(String.format("Integer part = %01.0f",iPart));
System.out.println(String.format("Fractional part = %01.04f",fPart));
Output:
Integer part = -0
Fractional part = 0,3500
Just put a div and update the content...
<script>
function setvideo(src) {
document.getElementById('div_video').innerHTML = '<video autoplay controls id="video_ctrl" style="height: 100px; width: 100px;"><source src="'+src+'" type="video/mp4"></video>';
document.getElementById('video_ctrl').play();
}
</script>
<button onClick="setvideo('video1.mp4');">Video1</button>
<div id="div_video"> </div>
Imho the best solution is:
fooBar | 0
This is used in asm.js to force integer type.
ApkTool to view resources inside APK File
apktool.bat d sampleApp.apk
Using dex2jar
dex2jar sampleApp.apk
Decompiling .jar using JD-GUI
$ lsof -wni tcp:3000
# Kill the running process
$ kill -9 5946
$ rm tmp/server.pids
foreman start etc start the service
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
In LINQ2SQL you seldom need to join explicitly when using inner joins.
If you have proper foreign key relationships in your database you will automatically get a relation in the LINQ designer (if not you can create a relation manually in the designer, although you should really have proper relations in your database)
Then you can just access related tables with the "dot-notation"
var q = from child in context.Childs
where child.Parent.col2 == 4
select new
{
childCol1 = child.col1,
parentCol1 = child.Parent.col1,
};
will generate the query
SELECT [t0].[col1] AS [childCol1], [t1].[col1] AS [parentCol1]
FROM [dbo].[Child] AS [t0]
INNER JOIN [dbo].[Parent] AS [t1] ON ([t1].[col1] = [t0].[col1]) AND ([t1].[col2] = [t0].[col2])
WHERE [t1].[col2] = @p0
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [4]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1
In my opinion this is much more readable and lets you concentrate on your special conditions and not the actual mechanics of the join.
Edit
This is of course only applicable when you want to join in the line with our database model. If you want to join "outside the model" you need to resort to manual joins as in the answer from Quintin Robinson
With all respect the most likely thing is that you are mistaken about why the click is being 'rejected'. Why do you think some program is trying to determine if it's human or not? The Robot class (have used it a lot) should send messages that the operating system has no way to distinguish from a user doing the click.
Put it in .gitignore
. But from the gitignore(5)
man page:
· If the pattern does not contain a slash /, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file (relative to the toplevel of the work tree if not from a .gitignore file). · Otherwise, git treats the pattern as a shell glob suitable for consumption by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will not match a / in the pathname. For example, "Documentation/*.html" matches "Documentation/git.html" but not "Documentation/ppc/ppc.html" or "tools/perf/Documentation/perf.html".
So, either specify the full path to the appropriate *.pyc
entry, or put it in a .gitignore
file in any of the directories leading from the repository root (inclusive).
I don't think the accepted solution handles the case where the error text is reported on stderr. From my testing the exception's output attribute did not contain the results from stderr and the docs warn against using stderr=PIPE in check_output(). Instead, I would suggest one small improvement to J.F Sebastian's solution by adding stderr support. We are, after all, trying to handle errors and stderr is where they are often reported.
from subprocess import Popen, PIPE
p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
if p.returncode != 0:
print("bitcoin failed %d %s %s" % (p.returncode, output, error))
According to @Data description you can use:
All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.
The underlining problem is simple – lack of permission to /var/run/docker.sock
unix domain socket.
From Daemon socket option chapter of Docker Command Line reference for Docker 1.6.0:
By default, a unix domain socket (or IPC socket) is created at
/var/run/docker.sock
, requiring either root permission, or docker group membership.
Steps necessary to grant rights to users are nicely described in Docker installation instructions for Fedora:
Granting rights to users to use Docker
The docker command line tool contacts the docker daemon process via a socket file
/var/run/docker.sock
owned byroot:root
. Though it's recommended to use sudo for docker commands, if users wish to avoid it, an administrator can create a docker group, have it own/var/run/docker.sock
, and add users to this group.
$ sudo groupadd docker
$ sudo chown root:docker /var/run/docker.sock
$ sudo usermod -a -G docker $USERNAME
Log out and log back in for above changes to take effect.
Please note that Docker packages of some Linux distributions (Ubuntu) do already place /var/run/docker.sock
in the docker
group making the first two of above steps unnecessary.
In case of OS X and boot2docker
the situation is different; the Docker daemon runs inside a VM so the DOCKER_HOST
environment variable must be set to this VM so that the Docker client could find the Docker daemon. This is done by running $(boot2docker shellinit)
in the shell.
We can add Unique key index by using fluent api. Below code worked for me
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Property(p => p.Email).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_EmailIndex") { IsUnique = true }));
}
It happens because Build Tools revision 24.4.1 doesn't exist.
The latest version is 23.0.2.
These tools is included in the SDK package and installed in the <sdk>/build-tools/
directory.
Don't confuse the Android SDK Tools with SDK Build Tools.
Change in your build.gradle
android {
buildToolsVersion "23.0.2"
// ...
}
Here is a generic set of code that I frequently use to rearrange the position of columns. You may find it useful.
cols = df.columns.tolist()
n = int(cols.index('Mid'))
cols = [cols[n]] + cols[:n] + cols[n+1:]
df = df[cols]
Most distributions have installed the GUI app file-roller which unpacks tar, zip, rpm and many more.
file-roller --extract-here package.rpm
This will extract the contents in the current directory.
mvn install "-Dsomeproperty=propety value"
In pom.xml:
<properties>
<someproperty> ${someproperty} </someproperty>
</properties>
Referred from this question
How to use a clock and do assertions
This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.
The key idea is that the process
blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.
library ieee;
use ieee.std_logic_1164.all;
entity counter_tb is
end counter_tb;
architecture behav of counter_tb is
constant width : natural := 2;
constant clk_period : time := 1 ns;
signal clk : std_logic := '0';
signal data : std_logic_vector(width-1 downto 0);
signal count : std_logic_vector(width-1 downto 0);
type io_t is record
load : std_logic;
data : std_logic_vector(width-1 downto 0);
count : std_logic_vector(width-1 downto 0);
end record;
type ios_t is array (natural range <>) of io_t;
constant ios : ios_t := (
('1', "00", "00"),
('0', "UU", "01"),
('0', "UU", "10"),
('0', "UU", "11"),
('1', "10", "10"),
('0', "UU", "11"),
('0', "UU", "00"),
('0', "UU", "01")
);
begin
counter_0: entity work.counter port map (clk, load, data, count);
process
begin
for i in ios'range loop
load <= ios(i).load;
data <= ios(i).data;
wait until falling_edge(clk);
assert count = ios(i).count;
end loop;
wait;
end process;
process
begin
for i in 1 to 2 * ios'length loop
wait for clk_period / 2;
clk <= not clk;
end loop;
wait;
end process;
end behav;
The counter would look like this:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned
entity counter is
generic (
width : in natural := 2
);
port (
clk, load : in std_logic;
data : in std_logic_vector(width-1 downto 0);
count : out std_logic_vector(width-1 downto 0)
);
end entity counter;
architecture rtl of counter is
signal cnt : unsigned(width-1 downto 0);
begin
process(clk) is
begin
if rising_edge(clk) then
if load = '1' then
cnt <= unsigned(data);
else
cnt <= cnt + 1;
end if;
end if;
end process;
count <= std_logic_vector(cnt);
end architecture rtl;
Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches
Brendan is correct. You can edit the Select command to edit a filtered list of records. For instance "WHERE dept_no = 200"
.
I already wrote a function for one of my projects that will comparing an object as a user options with its internal clone. It also can validate and even replace by default values if the user entered bad type of data or removed, in pure javascript.
In IE8 100% works. Tested successfully.
// ObjectKey: ["DataType, DefaultValue"]
reference = {
a : ["string", 'Defaul value for "a"'],
b : ["number", 300],
c : ["boolean", true],
d : {
da : ["boolean", true],
db : ["string", 'Defaul value for "db"'],
dc : {
dca : ["number", 200],
dcb : ["string", 'Default value for "dcb"'],
dcc : ["number", 500],
dcd : ["boolean", true]
},
dce : ["string", 'Default value for "dce"'],
},
e : ["number", 200],
f : ["boolean", 0],
g : ["", 'This is an internal extra parameter']
};
userOptions = {
a : 999, //Only string allowed
//b : ["number", 400], //User missed this parameter
c: "Hi", //Only lower case or case insitive in quotes true/false allowed.
d : {
da : false,
db : "HelloWorld",
dc : {
dca : 10,
dcb : "My String", //Space is not allowed for ID attr
dcc: "3thString", //Should not start with numbers
dcd : false
},
dce: "ANOTHER STRING",
},
e: 40,
f: true,
};
function compare(ref, obj) {
var validation = {
number: function (defaultValue, userValue) {
if(/^[0-9]+$/.test(userValue))
return userValue;
else return defaultValue;
},
string: function (defaultValue, userValue) {
if(/^[a-z][a-z0-9-_.:]{1,51}[^-_.:]$/i.test(userValue)) //This Regex is validating HTML tag "ID" attributes
return userValue;
else return defaultValue;
},
boolean: function (defaultValue, userValue) {
if (typeof userValue === 'boolean')
return userValue;
else return defaultValue;
}
};
for (var key in ref)
if (obj[key] && obj[key].constructor && obj[key].constructor === Object)
ref[key] = compare(ref[key], obj[key]);
else if(obj.hasOwnProperty(key))
ref[key] = validation[ref[key][0]](ref[key][1], obj[key]); //or without validation on user enties => ref[key] = obj[key]
else ref[key] = ref[key][1];
return ref;
}
//console.log(
alert(JSON.stringify( compare(reference, userOptions),null,2 ))
//);
/* result
{
"a": "Defaul value for \"a\"",
"b": 300,
"c": true,
"d": {
"da": false,
"db": "Defaul value for \"db\"",
"dc": {
"dca": 10,
"dcb": "Default value for \"dcb\"",
"dcc": 500,
"dcd": false
},
"dce": "Default value for \"dce\""
},
"e": 40,
"f": true,
"g": "This is an internal extra parameter"
}
*/
The original answer is that your path has to join prefix like Uri.parse("file://" + file.getPath);
Let's say your image is a 16x16 .png icon called icon.png Use the power of CSS!
CSS:
input#image-button{
background: #ccc url('icon.png') no-repeat top left;
padding-left: 16px;
height: 16px;
}
HTML:
<input type="submit" id="image-button" value="Text"></input>
This will put the image to the left of the text.
You can select the tables from information_schema
SELECT * FROM information_schema.tables
WHERE table_schema = 'public'
I got this error when tried to create folder http://localhost:8080/repository/default/parent/newFolder when http://localhost:8080/repository/default/parent didn't exist.
Looks like you have an extra parenthesis.
The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.
foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
})
git-pull - Fetch from and integrate with another repository or a local branch
git pull [options] [<repository> [<refspec>...]]
You can refer official git doc https://git-scm.com/docs/git-pull
Ex :
git pull origin dev
items is one attribute of dict object.maybe you can try
qs[0].items()
The compatibility table given in the tensorflow site does not contain specific minor versions for cuda and cuDNN. However, if the specific versions are not met, there will be an error when you try to use tensorflow.
For tensorflow-gpu==1.12.0
and cuda==9.0
, the compatible cuDNN
version is 7.1.4
, which can be downloaded from here after registration.
You can check your cuda version using
nvcc --version
cuDNN version using
cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2
tensorflow-gpu version using
pip freeze | grep tensorflow-gpu
UPDATE: Since tensorflow 2.0, has been released, I will share the compatible cuda and cuDNN versions for it as well (for Ubuntu 18.04).
tensorflow-gpu
= 2.0.0cuda
= 10.0cuDNN
= 7.6.0If you are like me and don't always retrieve the axes, ax
, when plotting the figure, then a simple solution would be to do
plt.xticks([])
plt.yticks([])
You may do it using xargs
if you like, but the main idea is still the same:
find *.txt | xargs -I{} sh -c "cat {}; echo ''" > finalfile.txt
For non-preemptive system,
waitingTime = startTime - arrivalTime
turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime
startTime = Time at which the process started executing
finishTime = Time at which the process finished executing
You can keep track of the current time elapsed in the system(timeElapsed
). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime
, when finishes, record its finishTime
(both same as timeElapsed
). That way you can calculate what you need.
If you don't mind importing the numpy package, it has a lot of convenient functionality built in. It's likely to be much more efficient to use their data structures than lists of lists, etc.
from __future__ import division
import numpy
data = numpy.asarray([1,2,3,4,5])
dists = data.reshape((1,5)) / data.reshape((5,1))
print dists
which = dists.argmin()
(r,c) = (which // 5, which % 5) # assumes C ordering
# pick whichever is most appropriate for you...
minval = dists[r,c]
minval = dists.min()
minval = dists.ravel()[which]
I would suggest in taking a look into JWE using special algorithms which is not present in jwt.io to decrypt
Reference link: https://www.npmjs.com/package/node-webtokens
jwt.generate('PBES2-HS512+A256KW', 'A256GCM', payload, pwd, (error, token) => {
jwt.parse(token).verify(pwd, (error, parsedToken) => {
// other statements
});
});
This answer may be too late or you might have already found out the way, but still, I felt it would be helpful for you and others as well.
A simple example which I have created: https://github.com/hansiemithun/jwe-example
I actually used this script to replace a line of code in the cron file on our company's UNIX servers awhile back. We executed it as normal shell script and had no problems:
#Create temporary file with new line in place
cat /dir/file | sed -e "s/the_original_line/the_new_line/" > /dir/temp_file
#Copy the new file over the original file
mv /dir/temp_file /dir/file
This doesn't go by line number, but you can easily switch to a line number based system by putting the line number before the s/
and placing a wildcard in place of the_original_line
.
if I got it right, you can try
for item in [x for x in checklist if x not in mylist]:
print (item)
This works with both text and numbers and doesn't care if there are blank cells, i.e., it will return the last non-blank cell.
It needs to be array-entered, meaning that you press Ctrl-Shift-Enter after you type or paste it in. The below is for column A:
=INDEX(A:A,MAX((A:A<>"")*(ROW(A:A))))
Here is what I uses to search for multiple words in multiple columns - SQL server
Hope my answer help someone :) Thanks
declare @searchTrm varchar(MAX)='one two three ddd 20 30 comment';
--select value from STRING_SPLIT(@searchTrm, ' ') where trim(value)<>''
select * from Bols
WHERE EXISTS (SELECT value
FROM STRING_SPLIT(@searchTrm, ' ')
WHERE
trim(value)<>''
and(
BolNumber like '%'+ value+'%'
or UserComment like '%'+ value+'%'
or RequesterId like '%'+ value+'%' )
)
Give them a trivial pom with these jars listed as dependencies and instructions to run:
mvn dependency:go-offline
This will pull the dependencies to the local repo.
A more direct solution is dependency:get, but it's a lot of arguments to type:
mvn dependency:get -DrepoUrl=something -Dartifact=group:artifact:version
"Actively refused it" means that the host sent a reset instead of an ack when you tried to connect. It is therefore not a problem in your code. Either there is a firewall blocking the connection or the process that is hosting the service is not listening on that port. This may be because it is not running at all or because it is listening on a different port.
Once you start the process hosting your service, try netstat -anb
(requires admin privileges) to verify that it is running and listening on the expected port.
update: On Linux you may need to do netstat -anp
instead.
Ok solved it.
Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting
In my app.js routing config:
$routeProvider.when('/pages/:name', {
templateUrl: '/pages/home.html',
controller: CMSController
});
Then in my CMS controller:
function CMSController($scope, $route, $routeParams) {
$route.current.templateUrl = '/pages/' + $routeParams.name + ".html";
$.get($route.current.templateUrl, function (data) {
$scope.$apply(function () {
$('#views').html($compile(data)($scope));
});
});
...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];
With #views being my <div id="views" ng-view></div>
So now it works with standard routing and dynamic routing.
To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio
into my browser and hey presto portfolio.html was displayed....
Updated Added $apply and $compile to the html so that dynamic content can be injected.
I don't understand why you want to use SELECT * FROM
as part of the statement.
If you want to set the background using a hex color you could do this:
var bc = new BrushConverter();
myTextBox.Background = (Brush)bc.ConvertFrom("#FFXXXXXX");
Or you could set up a SolidColorBrush resource in XAML, and then use findResource in the code-behind:
<SolidColorBrush x:Key="BrushFFXXXXXX">#FF8D8A8A</SolidColorBrush>
myTextBox.Background = (Brush)Application.Current.MainWindow.FindResource("BrushFFXXXXXX");
<select>
<option selected disabled>Choose one</option>
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
<option value="cromwell">Cromwell</option>
<option value="queenstown">Queenstown</option>
</select>
Using selected
and disabled
will make "Choose one" be the default selected value, but also make it impossible for the user to actually select the item, like so:
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
In your first example, the C# compiler will actually translate the using statement to the following:
SqlConnection connection = new SqlConnection(connectionString));
try
{
connection.Open();
string storedProc = "GetData";
SqlCommand command = new SqlCommand(storedProc, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
return (byte[])command.ExecuteScalar();
}
finally
{
connection.Dispose();
}
Finally statements will always get called before a function returns and so the connection will be always closed/disposed.
So, in your second example the code will be compiled to the following:
try
{
try
{
connection.Open();
string storedProc = "GetData";
SqlCommand command = new SqlCommand(storedProc, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
return (byte[])command.ExecuteScalar();
}
finally
{
connection.Dispose();
}
}
catch (Exception)
{
}
The exception will be caught in the finally statement and the connection closed. The exception will not be seen by the outer catch clause.
For nearly all programming purposes, VBA and VB 6.0 are the same thing.
VBA cannot compile your program into an executable binary. You'll always need the host (a Word file and MS Word, for example) to contain and execute your project. You'll also not be able to create COM DLLs with VBA.
Apart from that, there is a difference in the IDE - the VB 6.0 IDE is more powerful in comparison. On the other hand, you have tight integration of the host application in VBA. Application-global objects (like "ActiveDocument") and events are available without declaration, so application-specific programming is straight-forward.
Still, nothing keeps you from firing up Word, loading the VBA IDE and solving a problem that has no relation to Word whatsoever. I'm not sure if there is anything that VB 6.0 can do (technically), and VBA cannot. I'm looking for a comparison sheet on the MSDN though.
The problems were:
The solution based on omerkirk's answer involves:
autoOpen: false, width: "auto", height: "auto"
Here is a rough outline of code:
<div class="thumb">
<a href="http://jsfiddle.net/yBNVr/show/" data-title="Std 4:3 ratio video" data-width="512" data-height="384"><img src="http://dummyimage.com/120x90/000/f00&text=Std+4-3+ratio+video" /></a></li>
<a href="http://jsfiddle.net/yBNVr/1/show/" data-title="HD 16:9 ratio video" data-width="512" data-height="288"><img src="http://dummyimage.com/120x90/000/f00&text=HD+16-9+ratio+video" /></a></li>
</div>
$(function () {
var iframe = $('<iframe frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>');
var dialog = $("<div></div>").append(iframe).appendTo("body").dialog({
autoOpen: false,
modal: true,
resizable: false,
width: "auto",
height: "auto",
close: function () {
iframe.attr("src", "");
}
});
$(".thumb a").on("click", function (e) {
e.preventDefault();
var src = $(this).attr("href");
var title = $(this).attr("data-title");
var width = $(this).attr("data-width");
var height = $(this).attr("data-height");
iframe.attr({
width: +width,
height: +height,
src: src
});
dialog.dialog("option", "title", title).dialog("open");
});
});
Demo here and code here. And another example along similar lines
The console
object is available in Internet Explorer 8 or newer, but only if you open the Developer Tools window by pressing F12 or via the menu.
It stays available even if you close the Developer Tools window again until you close your IE.
Chorme and Opera always have an available console
, at least in the current versions. Firefox has a console
when using Firebug, but it may also provide one without Firebug.
In any case it is a save approach to make the use of console
output optional. Here are some examples on how to do that:
if (console) {
console.log('Hello World!');
}
if (console) console.debug('value of someVar: ' + someVar);
You can't load a controller from a controller in CI - unless you use HMVC or something.
You should think about your architecture a bit. If you need to call a controller method from another controller, then you should probably abstract that code out to a helper or library and call it from both controllers.
UPDATE
After reading your question again, I realize that your end goal is not necessarily HMVC, but URI manipulation. Correct me if I'm wrong, but it seems like you're trying to accomplish URLs with the first section being the method name and leave out the controller name altogether.
If this is the case, you'd get a cleaner solution by getting creative with your routes.
For a really basic example, say you have two controllers, controller1
and controller2
. Controller1
has a method method_1
- and controller2
has a method method_2
.
You can set up routes like this:
$route['method_1'] = "controller1/method_1";
$route['method_2'] = "controller2/method_2";
Then, you can call method 1 with a URL like http://site.com/method_1
and method 2 with http://site.com/method_2
.
Albeit, this is a hard-coded, very basic, example - but it could get you to where you need to be if all you need to do is remove the controller from the URL.
You could also go with remapping your controllers.
From the docs: "If your controller contains a function named _remap(), it will always get called regardless of what your URI contains.":
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->default_method();
}
}
Just in case anyone else visits this post I thought I'd describe what I did.
Right click on res folder > New image asset
browser to the icon. Click next
By default the icon goes to src/debug/res- keep this
In the project hierarchy, browse to src/debug/res and copy the files from the drawable* directories to the same directories in src/main and src/main
copy the src/debug/res/icon_name.png to the src/main and src/release directories
I will leave the way I do to submit the form without using the name
tag inside the form:
<button type="submit" onClick="placeOrder(this.form)">Place Order</button>
function placeOrder(form){
form.submit();
}
A better way, use getParent()
from File
Class..
String a="/root/sdcard/Pictures/img0001.jpg"; // A valid file path
File file = new File(a);
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null
http://developer.android.com/reference/java/io/File.html#getParent%28%29
answering your question 2:
I would use option b
simply because it consumes much less resources. with option 'a', every client will cause the server to consume a lot of memory, loading all the files you need (even though i like php, this is one of the problems with it). With option 'b' you can load your libraries (reusable code) and share them among all client requests.
But be ware that if you have multiple cores you should tweak node.js to use all of them.
Before creating a new branch always the best practice is to have the latest of repo in your local machine. Follow these steps for error free branch creation.
1. $ git branch (check which branches exist and which one is currently active (prefixed with *). This helps you avoid creating duplicate/confusing branch name)
2. $ git branch <new_branch> (creates new branch)
3. $ git checkout new_branch
4. $ git add . (After making changes in the current branch)
5. $ git commit -m "type commit msg here"
6. $ git checkout master (switch to master branch so that merging with new_branch can be done)
7. $ git merge new_branch (starts merging)
8. $ git push origin master (push to the remote server)
I referred this blog and I found it to be a cleaner approach.
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
There should also be a YEAR().
As for comparing, you could compare dates that are the first days of those years and months, or you could convert the year/month pair into a number suitable for comparison (i.e. bigger = later). (Exercise left to the reader. For hints, read about the ISO date format.)
Or you could use multiple comparisons (i.e. years first, then months).
This approach is not correct beacuse of Google Server Overload. For more informations see https://gis.stackexchange.com/questions/15052/how-to-avoid-google-map-geocode-limit#answer-15365
By the way, if you wish to proceed anyway, here you can find a code that let you load multiple markers ajax sourced on google maps avoiding OVER_QUERY_LIMIT error.
I've tested on my onw server and it works!:
var lost_addresses = [];
geocode_count = 0;
resNumber = 0;
map = new GMaps({
div: '#gmap_marker',
lat: 43.921493,
lng: 12.337646,
});
function loadMarkerTimeout(timeout) {
setTimeout(loadMarker, timeout)
}
function loadMarker() {
map.setZoom(6);
$.ajax({
url: [Insert here your URL] ,
type:'POST',
data: {
"action": "loadMarker"
},
success:function(result){
/***************************
* Assuming your ajax call
* return something like:
* array(
* 'status' => 'success',
* 'results'=> $resultsArray
* );
**************************/
var res=JSON.parse(result);
if(res.status == 'success') {
resNumber = res.results.length;
//Call the geoCoder function
getGeoCodeFor(map, res.results);
}
}//success
});//ajax
};//loadMarker()
$().ready(function(e) {
loadMarker();
});
//Geocoder function
function getGeoCodeFor(maps, addresses) {
$.each(addresses, function(i,e){
GMaps.geocode({
address: e.address,
callback: function(results, status) {
geocode_count++;
if (status == 'OK') {
//if the element is alreay in the array, remove it
lost_addresses = jQuery.grep(lost_addresses, function(value) {
return value != e;
});
latlng = results[0].geometry.location;
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
title: 'MyNewMarker',
});//addMarker
} else if (status == 'ZERO_RESULTS') {
//alert('Sorry, no results found');
} else if(status == 'OVER_QUERY_LIMIT') {
//if the element is not in the losts_addresses array, add it!
if( jQuery.inArray(e,lost_addresses) == -1) {
lost_addresses.push(e);
}
}
if(geocode_count == addresses.length) {
//set counter == 0 so it wont's stop next round
geocode_count = 0;
setTimeout(function() {
getGeoCodeFor(maps, lost_addresses);
}, 2500);
}
}//callback
});//GeoCode
});//each
};//getGeoCodeFor()
Example:
map = new GMaps({_x000D_
div: '#gmap_marker',_x000D_
lat: 43.921493,_x000D_
lng: 12.337646,_x000D_
});_x000D_
_x000D_
var jsonData = { _x000D_
"status":"success",_x000D_
"results":[ _x000D_
{ _x000D_
"customerId":1,_x000D_
"address":"Via Italia 43, Milano (MI)",_x000D_
"customerName":"MyAwesomeCustomer1"_x000D_
},_x000D_
{ _x000D_
"customerId":2,_x000D_
"address":"Via Roma 10, Roma (RM)",_x000D_
"customerName":"MyAwesomeCustomer2"_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
function loadMarkerTimeout(timeout) {_x000D_
setTimeout(loadMarker, timeout)_x000D_
}_x000D_
_x000D_
function loadMarker() { _x000D_
map.setZoom(6);_x000D_
_x000D_
$.ajax({_x000D_
url: '/echo/html/',_x000D_
type: "POST",_x000D_
data: jsonData,_x000D_
cache: false,_x000D_
success:function(result){_x000D_
_x000D_
var res=JSON.parse(result);_x000D_
if(res.status == 'success') {_x000D_
resNumber = res.results.length;_x000D_
//Call the geoCoder function_x000D_
getGeoCodeFor(map, res.results);_x000D_
}_x000D_
}//success_x000D_
});//ajax_x000D_
_x000D_
};//loadMarker()_x000D_
_x000D_
$().ready(function(e) {_x000D_
loadMarker();_x000D_
});_x000D_
_x000D_
//Geocoder function_x000D_
function getGeoCodeFor(maps, addresses) {_x000D_
$.each(addresses, function(i,e){ _x000D_
GMaps.geocode({_x000D_
address: e.address,_x000D_
callback: function(results, status) {_x000D_
geocode_count++; _x000D_
_x000D_
console.log('Id: '+e.customerId+' | Status: '+status);_x000D_
_x000D_
if (status == 'OK') { _x000D_
_x000D_
//if the element is alreay in the array, remove it_x000D_
lost_addresses = jQuery.grep(lost_addresses, function(value) {_x000D_
return value != e;_x000D_
});_x000D_
_x000D_
_x000D_
latlng = results[0].geometry.location;_x000D_
map.addMarker({_x000D_
lat: latlng.lat(),_x000D_
lng: latlng.lng(),_x000D_
title: e.customerName,_x000D_
});//addMarker_x000D_
} else if (status == 'ZERO_RESULTS') {_x000D_
//alert('Sorry, no results found');_x000D_
} else if(status == 'OVER_QUERY_LIMIT') {_x000D_
_x000D_
//if the element is not in the losts_addresses array, add it! _x000D_
if( jQuery.inArray(e,lost_addresses) == -1) {_x000D_
lost_addresses.push(e);_x000D_
}_x000D_
_x000D_
} _x000D_
_x000D_
if(geocode_count == addresses.length) {_x000D_
//set counter == 0 so it wont's stop next round_x000D_
geocode_count = 0;_x000D_
_x000D_
setTimeout(function() {_x000D_
getGeoCodeFor(maps, lost_addresses);_x000D_
}, 2500);_x000D_
}_x000D_
}//callback_x000D_
});//GeoCode_x000D_
});//each_x000D_
};//getGeoCodeFor()
_x000D_
#gmap_marker {_x000D_
min-height:250px;_x000D_
height:100%;_x000D_
width:100%;_x000D_
position: relative; _x000D_
overflow: hidden;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.24/gmaps.min.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<div id="gmap_marker"></div> <!-- /#gmap_marker -->
_x000D_
I tried using React.FormEvent<HTMLSelectElement>
but it led to an error in the editor, even though there is no EventTarget
visible in the code:
The property 'value' does not exist on value of type 'EventTarget'
Then I changed React.FormEvent
to React.ChangeEvent
and it helped:
private changeName(event: React.ChangeEvent<HTMLSelectElement>) {
event.preventDefault();
this.props.actions.changeName(event.target.value);
}
You can just convert the string like that [str intValue] or [str integerValue]
integerValue Returns the NSInteger value of the receiver’s text.
for more information refer here
The reason why what you want to do doesn't work is because of the logical order of operations in SQL, which, for your first query, is (simplified):
FROM MonitoringJob
SELECT Category, CreationDate
i.e. add a so called extended sort key columnORDER BY CreationDate DESC
SELECT Category
i.e. remove the extended sort key column again from the result.So, thanks to the SQL standard extended sort key column feature, it is totally possible to order by something that is not in the SELECT
clause, because it is being temporarily added to it behind the scenes.
DISTINCT
?If we add the DISTINCT
operation, it would be added between SELECT
and ORDER BY
:
FROM MonitoringJob
SELECT Category, CreationDate
DISTINCT
ORDER BY CreationDate DESC
SELECT Category
But now, with the extended sort key column CreationDate
, the semantics of the DISTINCT
operation has been changed, so the result will no longer be the same. This is not what we want, so both the SQL standard, and all reasonable databases forbid this usage.
It can be emulated with standard syntax as follows
SELECT Category
FROM (
SELECT Category, MAX(CreationDate) AS CreationDate
FROM MonitoringJob
GROUP BY Category
) t
ORDER BY CreationDate DESC
Or, just simply (in this case), as shown also by Prutswonder
SELECT Category, MAX(CreationDate) AS CreationDate
FROM MonitoringJob
GROUP BY Category
ORDER BY CreationDate DESC
I have blogged about SQL DISTINCT and ORDER BY more in detail here.
You could do this using SUMIF
. This allows you to SUM a value in a cell IF a value in another cell meets the specified criteria. Here's an example:
- A B
1 100 YES
2 100 YES
3 100 NO
Using the formula: =SUMIF(B1:B3, "YES", A1:A3)
, you will get the result of 200
.
Here's a screenshot of a working example I just did in Excel:
Be careful with permissions, it is problably you don't have some of them. You can see it in settings -> apps -> name of the application -> permissions -> active if not.
This solution is (only) for SQL Server 2005
You guys are lifesavers, but as @Dan Mork said, you need to add EXEC to the mix. What was tripping me up was:
:
context.Database.SqlQuery<EntityType>(
"EXEC ProcName @param1, @param2",
new SqlParameter("param1", param1),
new SqlParameter("param2", param2)
);
Similarly in Java, you can create a S4 class in R that encapsulates your information:
setClass(Class="Person",
representation(
height="numeric",
age="numeric"
)
)
Then your function can return an instance of this class:
myFunction = function(age=28, height=176){
return(new("Person",
age=age,
height=height))
}
and you can access your information:
aPerson = myFunction()
aPerson@age
aPerson@height
Shortcut Alt+Enter shows intention actions where you can choose "Add Javadoc".
you cannot access array (php array) from js try
<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
?>
and js
$(document).ready( function() {
$('#prev').click(function() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
$('#content1').html(result[0]);
},
});
});
});
Schemas contains Databases.
Databases are part of a Schema.
So, schemas > databases.
Schemas contains views, stored procedure(s), database(s), trigger(s) etc.
To set to default Excel type Date (defaulted to OS level locale /-> i.e. xlsx will look different when opened by a German or British person/ and flagged with an asterisk if you choose it in Excel's cell format chooser) you should:
CellStyle cellStyle = xssfWorkbook.createCellStyle();
cellStyle.setDataFormat((short)14);
cell.setCellStyle(cellStyle);
I did it with xlsx and it worked fine.
To get difference in months (both start and end inclusive), irrespective of dates:
DateTime start = new DateTime(2013, 1, 1);
DateTime end = new DateTime(2014, 2, 1);
var diffMonths = (end.Month + end.Year * 12) - (start.Month + start.Year * 12);
$( this ).find( 'li.target' ).css("border", "3px double red");
or
$( this ).children( 'li.target' ).css("border", "3px double red");
Use children
for immediate descendants, or find
for deeper elements.
$('.SeeMore2').click(function(){
var $this = $(this);
$this.toggleClass('SeeMore2');
if($this.hasClass('SeeMore2')){
$this.text('See More');
} else {
$this.text('See Less');
}
});
This should do it. You have to make sure you toggle the correct class and take out the "." from the hasClass
In Swift you can use following code.
if UIScreen.mainScreen().respondsToSelector(Selector("scale")) {
UIGraphicsBeginImageContextWithOptions(self.window!.bounds.size, false, UIScreen.mainScreen().scale)
}
else{
UIGraphicsBeginImageContext(self.window!.bounds.size)
}
self.window?.layer.renderInContext(UIGraphicsGetCurrentContext())
var image : UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
I ran into this issue as well and found this post. Ultimately none of these answers solved my problem, instead I had to put in a rewrite rule to strip out the location /rt
as the backend my developers made was not expecting any additional paths:
+-(william@wkstn18)--(Thu, 05 Nov 20)-+
+-(~)--(16:13)->wscat -c ws://WebsocketServerHostname/rt
error: Unexpected server response: 502
Testing with wscat repeatedly gave a 502 response. Nginx error logs provided the same upstream error as above, but notice the upstream string shows the GET Request is attempting to access localhost:12775/rt and not localhost:12775:
2020/11/05 22:13:32 [error] 10175#10175: *7 upstream prematurely closed
connection while reading response header from upstream, client: WANIP,
server: WebsocketServerHostname, request: "GET /rt/socket.io/?transport=websocket
HTTP/1.1", upstream: "http://127.0.0.1:12775/rt/socket.io/?transport=websocket",
host: "WebsocketServerHostname"
Since the devs had not coded their websocket (listening on 12775) to expect /rt/socket.io but instead just /socket.io/ (NOTE: /socket.io/ appears to just be a way to specify websocket transport discussed here). Because of this, rather than ask them to rewrite their socket code I just put in a rewrite rule to translate WebsocketServerHostname/rt to WebsocketServerHostname:12775 as below:
upstream websocket-rt {
ip_hash;
server 127.0.0.1:12775;
}
server {
listen 80;
server_name WebsocketServerHostname;
location /rt {
proxy_http_version 1.1;
#rewrite /rt/ out of all requests and proxy_pass to 12775
rewrite /rt/(.*) /$1 break;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://websocket-rt;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
Easy way is to use Let keyword. This works for me.
from AItem in Db.A
Let BItem = Db.B.Where(x => x.id == AItem.id ).FirstOrDefault()
Where SomeCondition
Select new YourViewModel
{
X1 = AItem.a,
X2 = AItem.b,
X3 = BItem.c
}
This is a simulation of Left Join. If each item in B table not match to A item , BItem return null
You may try
pip install [email protected]/my_name/my_repo.git
without ssh:...
. That works for me.
Find spring-boot-starter-test in your pom.xml and modify it as follows:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
<scope>test</scope>
</dependency>
It fixed error like:
_Caused by: java.lang.IllegalArgumentException:_ **LoggerFactory** is not a **Logback LoggerContext** but *Logback* is on the classpath.
Either remove **Logback** or the competing implementation
(_class org.apache.logging.slf4j.Log4jLoggerFactory_
loaded from file:
**${M2_HOME}/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.6.2/log4j-slf4j-impl-2.6.2.jar**).
If you are using WebLogic you will need to add **'org.slf4j'** to prefer-application-packages in WEB-INF/weblogic.xml: **org.apache.logging.slf4j.Log4jLoggerFactory**
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
Information provided by @Gord
As of September 2019 pywin32
is now available from PyPI and installs the latest version (currently version 224). This is done via the pip
command
pip install pywin32
If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx
is the version you require, e.g. 224
pip install pywin32==xxx
This differs to the pip
command below as that one uses pypiwin32
which currently installs an older (namely 223)
Browsing the docs I see no reason for these commands to work for all python3.x
versions, I am unsure on python2.7
and below so you would have to try them and if they do not work then the solutions below will work.
Probably now undesirable solutions but certainly still valid as of September 2019
There is no version of specific version ofwin32api
. You have to get the pywin32
module which currently cannot be installed via pip
. It is only available from this link at the moment.
https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/
The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python
version :)
EDIT
Since I posted my answer there are other alternatives to downloading the win32api
module.
It is now available to download through pip
using this command;
pip install pypiwin32
Also it can be installed from this GitHub repository as provided in comments by @Heath
As @EastOcean said, We can add it by choosing Run/Debug configurations option. In my case, I have to set configuration for junit. So on clicking Edit configurations option, a pop up window is displayed. Then followed the below steps:
Save and run.
Thank you.
Write "var" before variables, when you define them. IE8 dies when there is no "var".
Based on this test (for-vs-forEach-vs-reduce) and this (loops)
I can say that:
var total = 0;
for (var i = 0, n = array.length; i < n; ++i)
{
total += array[i];
}
For you case you won't need this, but it adds a lot of flexibility.
Array.prototype.Aggregate = function(fn) {
var current
, length = this.length;
if (length == 0) throw "Reduce of empty array with no initial value";
current = this[0];
for (var i = 1; i < length; ++i)
{
current = fn(current, this[i]);
}
return current;
};
Usage:
var total = array.Aggregate(function(a,b){ return a + b });
Then comes forEach
and reduce
which have almost the same performance and varies from browser to browser, but they have the worst performance anyway.
I am working on a program that saves its data properly to %APPDATA%, but sometimes, there are system-wide settings that affect all users. So in these situations, it HAS to write to the programs installation directory.
And as far as I have read now, it's impossible to temporarily get write access to one directory. You can only run the whole application as administrator (which should be out of the question) or not be able to save that file. (all or nothing)
I guess, I will just write the file to %APPDATA% and launch an external program that copies the file into the installation folder and have THAT program demand admin privileges... dumb idea, but seems to be the only practical solution...
I had the same issue on windows 10, after trying all the previous solution the problem persists so I decided to uninstall my python 2.7 and install the version 2.7.13 and it works perfectly.
If you are on Ubuntu 17.04 (Zesty), and you literally just need the SDK (no Android Studio), you can install it like on Debian:
build.gradle
, change compileSdkVersion
to 23
and buildToolsVersion
to 24.0.0
gradle build
you can reset your branch with HEAD
git reset --hard branch_name
then fetch branches and delete branches which are not on remote from local,
git fetch -p
You can potentially roll your own Stream
variant by wrapping your lambda to throw an unchecked exception and then later unwrapping that unchecked exception on terminal operations:
@FunctionalInterface
public interface ThrowingPredicate<T, X extends Throwable> {
public boolean test(T t) throws X;
}
@FunctionalInterface
public interface ThrowingFunction<T, R, X extends Throwable> {
public R apply(T t) throws X;
}
@FunctionalInterface
public interface ThrowingSupplier<R, X extends Throwable> {
public R get() throws X;
}
public interface ThrowingStream<T, X extends Throwable> {
public ThrowingStream<T, X> filter(
ThrowingPredicate<? super T, ? extends X> predicate);
public <R> ThrowingStream<T, R> map(
ThrowingFunction<? super T, ? extends R, ? extends X> mapper);
public <A, R> R collect(Collector<? super T, A, R> collector) throws X;
// etc
}
class StreamAdapter<T, X extends Throwable> implements ThrowingStream<T, X> {
private static class AdapterException extends RuntimeException {
public AdapterException(Throwable cause) {
super(cause);
}
}
private final Stream<T> delegate;
private final Class<X> x;
StreamAdapter(Stream<T> delegate, Class<X> x) {
this.delegate = delegate;
this.x = x;
}
private <R> R maskException(ThrowingSupplier<R, X> method) {
try {
return method.get();
} catch (Throwable t) {
if (x.isInstance(t)) {
throw new AdapterException(t);
} else {
throw t;
}
}
}
@Override
public ThrowingStream<T, X> filter(ThrowingPredicate<T, X> predicate) {
return new StreamAdapter<>(
delegate.filter(t -> maskException(() -> predicate.test(t))), x);
}
@Override
public <R> ThrowingStream<R, X> map(ThrowingFunction<T, R, X> mapper) {
return new StreamAdapter<>(
delegate.map(t -> maskException(() -> mapper.apply(t))), x);
}
private <R> R unmaskException(Supplier<R> method) throws X {
try {
return method.get();
} catch (AdapterException e) {
throw x.cast(e.getCause());
}
}
@Override
public <A, R> R collect(Collector<T, A, R> collector) throws X {
return unmaskException(() -> delegate.collect(collector));
}
}
Then you could use this the same exact way as a Stream
:
Stream<Account> s = accounts.values().stream();
ThrowingStream<Account, IOException> ts = new StreamAdapter<>(s, IOException.class);
return ts.filter(Account::isActive).map(Account::getNumber).collect(toSet());
This solution would require quite a bit of boilerplate, so I suggest you take a look at the library I already made which does exactly what I have described here for the entire Stream
class (and more!).
This is a known issue of the mssql ODBC driver. According to the Microsoft blog post:
The ColumnSize parameter of SQLBindParameter refers to the number of characters in the SQL type, while BufferLength is the number of bytes in the application's buffer. However, if the SQL data type is varchar(n) or char(n), the application binds the parameter as SQL_C_CHAR or SQL_C_VARCHAR, and the character encoding of the client is UTF-8, you may get a "String data, right truncation" error from the driver even if the value of ColumnSize is aligned with the size of the data type on the server. This error occurs since conversions between character encodings may change the length of the data. For example, a right apostrophe character (U+2019) is encoded in CP-1252 as the single byte 0x92, but in UTF-8 as the 3-byte sequence 0xe2 0x80 0x99.
You can find the full article here.
Make sure the user you are using to access your database has the privileges to do so.
GRANT ALL PRIVILEGES ON * . * TO 'user'@'localhost';
Where the first star can be replaced by database name, second star specifies table. Make sure to flush privileges after.
Use String.fromCharCode
. This returns a string from a Unicode value, which matches the first 128 characters of ASCII.
var a = String.fromCharCode(97);
When you are done with using your Connection
, you need to explicitly close it by calling its close()
method in order to release any other database resources (cursors, handles, etc.) the connection may be holding on to.
Actually, the safe pattern in Java is to close your ResultSet
, Statement
, and Connection
(in that order) in a finally
block when you are done with them. Something like this:
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// Do stuff
...
} catch (SQLException ex) {
// Exception handling stuff
...
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* Ignored */}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) { /* Ignored */}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) { /* Ignored */}
}
}
The finally
block can be slightly improved into (to avoid the null check):
} finally {
try { rs.close(); } catch (Exception e) { /* Ignored */ }
try { ps.close(); } catch (Exception e) { /* Ignored */ }
try { conn.close(); } catch (Exception e) { /* Ignored */ }
}
But, still, this is extremely verbose so you generally end up using an helper class to close the objects in null-safe helper methods and the finally
block becomes something like this:
} finally {
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
DbUtils.closeQuietly(conn);
}
And, actually, the Apache Commons DbUtils has a DbUtils
class which is precisely doing that, so there isn't any need to write your own.
Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.
In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
//your operations on file
} else {
String name = item.getFieldName();
String value = item.getString();
//you operations on paramters
}
}
You could simply do
d % 1 == 0
to check if double d
is a whole.
I encountered the same thing. In package.json, change mongodb line to "mongodb": "^2.2.33". You will need to npm uninstall mongodb; then npm install to install this version.
This resolved the issue for me. Seems to be a bug or docs need to be updated.
To Send bold,italic,fixed width code you can use this :
# Sending a HTML formatted message
bot.send_message(chat_id=@yourchannelname,
text="*boldtext* _italictext_ `fixed width font` [link] (http://google.com).",
parse_mode=telegram.ParseMode.MARKDOWN)
make sure you have enabled the bot as your admin .Then only it can send message
You can use django's filter
with datetime.date
objects:
import datetime
samples = Sample.objects.filter(sampledate__gte=datetime.date(2011, 1, 1),
sampledate__lte=datetime.date(2011, 1, 31))
Try this, which I think makes it clear. the underlying array is changed but our slice is not, print
just prints len()
chars, by another slice to the cap()
, you can see the changed array:
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
Test(a)
fmt.Println(a) // prints [0..6]
fmt.Println(a[:cap(a)] // prints [0..6,100]
}
I use the following with a MSSQL server:
if (DB_NAME() = 'YOUR_DATABASE')
begin
while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
begin
declare @sql nvarchar(2000)
SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
FROM information_schema.table_constraints
WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
exec (@sql)
PRINT @sql
end
while(exists(select 1 from INFORMATION_SCHEMA.TABLES))
begin
declare @sql2 nvarchar(2000)
SELECT TOP 1 @sql2=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
FROM INFORMATION_SCHEMA.TABLES
exec (@sql2)
PRINT @sql2
end
end
else
print('Only run this script on the development server!!!!')
Replace YOUR_DATABASE with the name of your database or remove the entire IF statement (I like the added safety).
In addition to setting the registry entry for AuthServerWhitelist you should also set AuthSchemes: "ntlm,negotiate" (or just "ntlm" as appropriate for your situation). Using the above templates the policy for that will be "Supported authentication schemes"
center-block
is bad idea as it covers a portion on your screen and you cannot click on your fields or buttons.
col-md-offset-?
is better option.
Use col-md-offset-3
is better option if class is col-sm-6
. Just change the number to center your block.
You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[]
in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer
(expecting Serializable
, and using ObjectOutputStream
). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.
I guess you can copy the entire package and make use of it.
You may had set different passwords for user 'root' or have been changed your password. I had same error as :
mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES)
and I found that my root password for phpmyAdmin is not same on both 'mysql' and 'phpmyadmin' databases, so I updated my password for 'phpmyadmin' database same as 'mysql' database as follow:
sudo gedit /etc/phpmyadmin/config-db.php
and update the fields
$dbuser='root';
$dbpass='myNewPassword'; <-- update your new password here
Best wishes!
I think you can find it usefull
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources
It shows how to define multiple datasources & assign one of them as primary.
Here is a rather full example, also contains distributes transactions - if you need it.
What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.
Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with @ConfigurationProperties annotation. Here is an example of this:
http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html
Hope these helps.
this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in this case:
you specify
transaction_status varchar(10)
but you actually trying to store
_transaction_status
which contain 19 characters.
that's why you faced this type of error in this code..
I was having the same sort of problem. Apparently it's simply because PHP doesn't recognise utf-8.
I was tearing my hair out at first when a '£' sign kept showing up as '£', despite it appearing ok in DreamWeaver. Eventually I remembered I had been having problems with links relative to the index file, when the pages, if viewed directly would work with slideshows, but not when used with an include (but that's beside the point. Anyway I wondered if this might be a similar problem, so instead of putting into the page that I was having problems with, I simply put it into the index.php file - problem fixed throughout.
Ookii folder dialog can be found at Nuget.
PM> Install-Package Ookii.Dialogs.Wpf
And, example code is as below.
var dialog = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog();
if (dialog.ShowDialog(this).GetValueOrDefault())
{
textBoxFolderPath.Text = dialog.SelectedPath;
}
More information on how to use it: https://github.com/augustoproiete/ookii-dialogs-wpf