string strConn = "Data Source=ORCL134; User ID=user; Password=psd;";
System.Data.OracleClient.OracleConnection con = newSystem.Data.OracleClient.OracleConnection(strConn);
con.Open();
System.Data.OracleClient.OracleCommand Cmd =
new System.Data.OracleClient.OracleCommand(
"SELECT * FROM TBLE_Name WHERE ColumnName_year= :year", con);
//for oracle..it is :object_name and for sql it s @object_name
Cmd.Parameters.Add(new System.Data.OracleClient.OracleParameter("year", (txtFinYear.Text).ToString()));
System.Data.OracleClient.OracleDataAdapter da = new System.Data.OracleClient.OracleDataAdapter(Cmd);
DataSet myDS = new DataSet();
da.Fill(myDS);
try
{
lblBatch.Text = "Batch Number is : " + Convert.ToString(myDS.Tables[0].Rows[0][19]);
lblBatch.ForeColor = System.Drawing.Color.Green;
lblBatch.Visible = true;
}
catch
{
lblBatch.Text = "No Data Found for the Year : " + txtFinYear.Text;
lblBatch.ForeColor = System.Drawing.Color.Red;
lblBatch.Visible = true;
}
da.Dispose();
con.Close();
Can I use (http://caniuse.com/#feat=datauri) shows support across the major browsers with few issues on IE.
(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :
Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.
This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).
Here's a nice answer from the FAQ on the scipy.org website:
What advantages do NumPy arrays offer over (nested) Python lists?
Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate. However, they have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. This also means that very few list operations can be carried out by efficient C loops – each iteration would require type checks and other Python API bookkeeping.
Above queries are good for finding the amount of space used by the table (indexes included), but if you want to compare how much space is used by indexes on the table use this query:
SELECT
OBJECT_NAME(i.OBJECT_ID) AS TableName,
i.name AS IndexName,
i.index_id AS IndexID,
8 * SUM(a.used_pages) AS 'Indexsize(KB)'
FROM
sys.indexes AS i
JOIN sys.partitions AS p ON p.OBJECT_ID = i.OBJECT_ID AND p.index_id = i.index_id
JOIN sys.allocation_units AS a ON a.container_id = p.partition_id
WHERE
i.is_primary_key = 0 -- fix for size discrepancy
GROUP BY
i.OBJECT_ID,
i.index_id,
i.name
ORDER BY
OBJECT_NAME(i.OBJECT_ID),
i.index_id
Here's my way to find file names that contain some content that I'm interested in, just a single bash line that nicely handles spaces in filenames too:
find . -name \*.xml | while read i; do grep '<?xml' "$i" >/dev/null; [ $? == 0 ] && echo $i; done
The first answer covers it.
Im guessing that somewhere down the line you may decide to store your info in a different class/structure. In that case you probably wouldn't want the results going in to an array from the split() method.
You didn't ask for it, but I'm bored, so here is an example, hope it's helpful.
This might be the class you write to represent a single person:
class Person {
public String firstName;
public String lastName;
public int id;
public int age;
public Person(String firstName, String lastName, int id, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.age = age;
}
// Add 'get' and 'set' method if you want to make the attributes private rather than public.
}
Then, the version of the parsing code you originally posted would look something like this: (This stores them in a LinkedList, you could use something else like a Hashtable, etc..)
try
{
String ruta="entrada.al";
BufferedReader reader = new BufferedReader(new FileReader(ruta));
LinkedList<Person> list = new LinkedList<Person>();
String line = null;
while ((line=reader.readLine())!=null)
{
if (!(line.equals("%")))
{
StringTokenizer st = new StringTokenizer(line, "*");
if (st.countTokens() == 4)
list.add(new Person(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken)));
else
// whatever you want to do to account for an invalid entry
// in your file. (not 4 '*' delimiters on a line). Or you
// could write the 'if' clause differently to account for it
}
}
reader.close();
}
<div class="FieldElement"><input /></div>
<div class="searchIcon"><input type="submit" /></div>
.FieldElement input {
width: 413px;
border:1px solid #ccc;
padding: 0 2.5em 0 0.5em;
}
.searchIcon
{
background: url(searchicon-image-path) no-repeat;
width: 17px;
height: 17px;
text-indent: -999em;
display: inline-block;
left: 432px;
top: 9px;
}
.FieldElement input {
width: 380px;
border:0;
}
.FieldElement {
border:1px solid #ccc;
width: 455px;
}
.searchIcon
{
background: url(searchicon-image-path) no-repeat;
width: 17px;
height: 17px;
text-indent: -999em;
display: inline-block;
left: 432px;
top: 9px;
}
This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").
import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;
public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
// PKCS#8 format
final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";
// PKCS#1 format
final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";
Path path = Paths.get(pemFileName.getAbsolutePath());
String privateKeyPem = new String(Files.readAllBytes(path));
if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
privateKeyPem = privateKeyPem.replaceAll("\\s", "");
byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));
} else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) { // PKCS#1 format
privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
privateKeyPem = privateKeyPem.replaceAll("\\s", "");
DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));
DerValue[] seq = derReader.getSequence(0);
if (seq.length < 9) {
throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
}
// skip version seq[0];
BigInteger modulus = seq[1].getBigInteger();
BigInteger publicExp = seq[2].getBigInteger();
BigInteger privateExp = seq[3].getBigInteger();
BigInteger prime1 = seq[4].getBigInteger();
BigInteger prime2 = seq[5].getBigInteger();
BigInteger exp1 = seq[6].getBigInteger();
BigInteger exp2 = seq[7].getBigInteger();
BigInteger crtCoef = seq[8].getBigInteger();
RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(keySpec);
}
throw new GeneralSecurityException("Not supported format of a private key");
}
<img src="images/no-record-found.png" width="50%" height="50%"/>
Your images folder and your index.html should be in same directory(follow following dir structure). it will even work after build
Directory Structure
-src
|-images
|-index.html
|-app
Compiler shows following error :
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Storyboard (<UIStoryboard: 0x7fedf2d5c9a0>) doesn't contain a
ViewController with identifier 'SBAddEmployeeVC''
Here the object of the storyboard created is not the main storyboard which contains our ViewControllers. As storyboard file on which we work is named as Main.storyboard. So we need to have reference of object of the Main.storyboard.
Use following code for that :
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
Here storyboardWithName
is the name of the storyboard file we are working with and bundle
specifies the bundle in which our storyboard is (i.e. mainBundle
).
If you dont want your local changes, then do below command to ignore(delete permanently) the local changes.
git checkout <filename>
or git checkout -- .
)git reset <filename>
or git reset
) and then do checkout (git checkout <filename>
or git checkout -- .
)git clean -fd
)If you dont want to loose your local changes, then stash it and do pull or rebase. Later merge your changes from stash.
git stash
, and then get latest changes from repo git pull orign master
or git rebase origin/master
, and then merge your changes from stash git stash pop stash@{0}
If you specify CSS attributes for your body
element it should apply to anything within <body></body>
so long as you don't override them later in the stylesheet.
In Django 2.* you can use this construction in views.py
def handler404(request, exception):
return render(request, 'errors/404.html', locals())
In settings.py
DEBUG = False
if DEBUG is False:
ALLOWED_HOSTS = [
'127.0.0.1:8000',
'*',
]
if DEBUG is True:
ALLOWED_HOSTS = []
In urls.py
# https://docs.djangoproject.com/en/2.0/topics/http/views/#customizing-error-views
handler404 = 'YOUR_APP_NAME.views.handler404'
Usually i creating default_app and handle site-wide errors, context processors in it.
Accidentally i stumbled upon another way to do a force kill on Unix (for those who use Weblogic). This is cheaper and more elegant than running /bin/kill -9 via Runtime.exec().
import weblogic.nodemanager.util.Platform;
import weblogic.nodemanager.util.ProcessControl;
...
ProcessControl pctl = Platform.getProcessControl();
pctl.killProcess(pid);
And if you struggle to get the pid, you can use reflection on java.lang.UNIXProcess, e.g.:
Process proc = Runtime.getRuntime().exec(cmdarray, envp);
if (proc instanceof UNIXProcess) {
Field f = proc.getClass().getDeclaredField("pid");
f.setAccessible(true);
int pid = f.get(proc);
}
Spring works in standalone application. You are using the wrong way to create a spring bean. The correct way to do it like this:
@Component
public class Main {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("META-INF/config.xml");
Main p = context.getBean(Main.class);
p.start(args);
}
@Autowired
private MyBean myBean;
private void start(String[] args) {
System.out.println("my beans method: " + myBean.getStr());
}
}
@Service
public class MyBean {
public String getStr() {
return "string";
}
}
In the first case (the one in the question), you are creating the object by yourself, rather than getting it from the Spring context. So Spring does not get a chance to Autowire
the dependencies (which causes the NullPointerException
).
In the second case (the one in this answer), you get the bean from the Spring context and hence it is Spring managed and Spring takes care of autowiring
.
I found an easier solution than I think given by the ones above and easier than rolling your own. I simply created a small rating bar, then added an onTouchListener to it. From there I compute the width of the click and determine the number of stars from that. Having used this several times, the only quirk I've found is that drawing of a small rating bar doesn't always turn out right in a table unless I enclose it in a LinearLayout (looks right in the editor, but not the device). Anyway, in my layout:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RatingBar
android:id="@+id/myRatingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5" />
</LinearLayout>
and within my activity:
final RatingBar minimumRating = (RatingBar)findViewById(R.id.myRatingBar);
minimumRating.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
float touchPositionX = event.getX();
float width = minimumRating.getWidth();
float starsf = (touchPositionX / width) * 5.0f;
int stars = (int)starsf + 1;
minimumRating.setRating(stars);
return true;
}
});
I hope this helps someone else. Definitely easier than drawing one's own (although I've found that also works, but I just wanted an easy use of stars).
If your repo have 2FA enabled. Highly suggest to use the app provided by github.com Here is the link: https://desktop.github.com/
After you downloaded it and installed it. Follow the withard, the app will ask you to provide the one time password for login. Once you filled in the one time password, you could see your repo/projects now.
Maybe it would be better if you would read your excel file from PHP, and then either save it to a DB or do some processing on it.
here an in-dept tutorial on how to read and write Excel data with PHP:
http://www.ibm.com/developerworks/opensource/library/os-phpexcel/index.html
Check out these docs:
If you started it in a terminal you should be ok with a ctrl + 'c'
-- this will do a clean shutdown.
However, if you are using launchctl there are specific instructions for that which will vary depending on how it was installed.
If you are using Homebrew it would be launchctl stop homebrew.mxcl.mongodb
According to the WWDC 713_hd_whats_new_in_ios_notifications. The previous size limit of 256 bytes for a push payload has now been increased to 2 kilobytes for iOS 8.
Source: http://asciiwwdc.com/2014/sessions/713?q=notification#1414.0
There is no way to do this with slf4j
.
I imagine that the reason that this functionality is missing is that it is next to impossible to construct a Level
type for slf4j
that can be efficiently mapped to the Level
(or equivalent) type used in all of the possible logging implementations behind the facade. Alternatively, the designers decided that your use-case is too unusual to justify the overheads of supporting it.
Concerning @ripper234's use-case (unit testing), I think the pragmatic solution is modify the unit test(s) to hard-wire knowledge of what logging system is behind the slf4j facade ... when running the unit tests.
People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">
Here is a very simple way to do what you want. In my case, it was getting Gradle to work (for Android Studio).
Run the following command:
sudo nano /etc/paths
or sudo vim /etc/paths
Enter your password, when prompted.
Open a new terminal window then type:
echo $PATH
You should see the new path appended to the end of the PATH.
I got these details from this post:
A better solution might be to introduce a license file with a counter. Write into the license file the install date of the application (during installation). Then everytime the application is run you can edit the license file and increment the count by 1. Each time the application starts up you just do a quick check to see if the 30 uses of the application has been reached i.e.
if (LicenseFile.Counter == 30)
// go into expired mode
Also this will solve the issue if the user has put the system clock back as you can do a simple check to say
if (LicenseFile.InstallationDate < SystemDate)
// go into expired mode (as punishment for trying to trick the app!)
The problem with your current setup is the user will have to use the application every day for 30 days to get their full 30 day trial.
Use the make_response method to get a response with your data. Then set the mimetype attribute. Finally return this response:
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
resp = app.make_response(xml)
resp.mimetype = "text/xml"
return resp
If you use Response
directly, you lose the chance to customize the responses by setting app.response_class
. The make_response
method uses the app.responses_class
to make the response object. In this you can create your own class, add make your application uses it globally:
class MyResponse(app.response_class):
def __init__(self, *args, **kwargs):
super(MyResponse, self).__init__(*args, **kwargs)
self.set_cookie("last-visit", time.ctime())
app.response_class = MyResponse
In case you use jQuery you need to wait for $(window).load
, because the embedded SVG document might not be yet loaded at $(document).ready
$(window).load(function () {
//alert("Document loaded, including graphics and embedded documents (like SVG)");
var a = document.getElementById("alphasvg");
//get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
//get the inner element by id
var delta = svgDoc.getElementById("delta");
delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});
select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
from MyTable
group by time
Output:
| TIME | COUNT |
-----------------
| 13:00 | 2 |
| 13:15 | 2 |
| 13:30 | 0 |
| 13:45 | 1 |
If you want to count all the activities in one query, you can do:
select time,
coalesce(count(case when activities = 1 then 1 end), 0) as count1,
coalesce(count(case when activities = 2 then 1 end), 0) as count2,
coalesce(count(case when activities = 3 then 1 end), 0) as count3,
coalesce(count(case when activities = 4 then 1 end), 0) as count4,
coalesce(count(case when activities = 5 then 1 end), 0) as count5
from MyTable
group by time
The advantage of this over grouping by activities, is that it will return a count of 0 even if there are no activites of that type for that time segment.
Of course, this will not return rows for time segments with no activities of any type. If you need that, you'll need to use a left join with table that lists all the possible time segments.
To remove message on logcat, i add a subtitle to track. On windows, right click on track -> Property -> Details -> insert a text on subtitle. Done :)
# Print In One Line Python
print('Enter Value')
n = int(input())
print(*range(1, n+1), sep="")
What about anonymous fields? I'm not sure if that will constitute a "nested struct" but it's cleaner than having a nested struct declaration. What if you want to reuse the nested element elsewhere?
type NestedElement struct{
someNumber int `json:"number"`
someString string `json:"string"`
}
type BaseElement struct {
NestedElement `json:"bar"`
}
just change the content-type to application/json when you use JSON with POST/PUT, etc...
the second argument in ROUNDUP, eg =ROUNDUP(12345.6789,3) refers to the negative of the base-10 column with that power of 10, that you want rounded up. eg 1000 = 10^3, so to round up to the next highest 1000, use ,-3)
=ROUNDUP(12345.6789,-4) = 20,000
=ROUNDUP(12345.6789,-3) = 13,000
=ROUNDUP(12345.6789,-2) = 12,400
=ROUNDUP(12345.6789,-1) = 12,350
=ROUNDUP(12345.6789,0) = 12,346
=ROUNDUP(12345.6789,1) = 12,345.7
=ROUNDUP(12345.6789,2) = 12,345.68
=ROUNDUP(12345.6789,3) = 12,345.679
So, to answer your question: if your value is in A1, use =ROUNDUP(A1,-1)
If the sheet already has a filter on it then:
Sub Macro1()
Cells.AutoFilter
End Sub
will remove it.
The jquery BalusC's solution improved by me. Used also: Brad Robertson's comment here.
Just put this in a .js, use the wide class for your desired combos and don't forge to give it an Id. Call the function in the onload (or documentReady or whatever).
As simple ass that :)
It will use the width that you defined for the combo as minimun length.
function fixIeCombos() {
if ($.browser.msie && $.browser.version < 9) {
var style = $('<style>select.expand { width: auto; }</style>');
$('html > head').append(style);
var defaultWidth = "200";
// get predefined combo's widths.
var widths = new Array();
$('select.wide').each(function() {
var width = $(this).width();
if (!width) {
width = defaultWidth;
}
widths[$(this).attr('id')] = width;
});
$('select.wide')
.bind('focus mouseover', function() {
// We're going to do the expansion only if the resultant size is bigger
// than the original size of the combo.
// In order to find out the resultant size, we first clon the combo as
// a hidden element, add to the dom, and then test the width.
var originalWidth = widths[$(this).attr('id')];
var $selectClone = $(this).clone();
$selectClone.addClass('expand').hide();
$(this).after( $selectClone );
var expandedWidth = $selectClone.width()
$selectClone.remove();
if (expandedWidth > originalWidth) {
$(this).addClass('expand').removeClass('clicked');
}
})
.bind('click', function() {
$(this).toggleClass('clicked');
})
.bind('mouseout', function() {
if (!$(this).hasClass('clicked')) {
$(this).removeClass('expand');
}
})
.bind('blur', function() {
$(this).removeClass('expand clicked');
})
}
}
iOS7 onwards, we have below default methods :
- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates
Calling above method is faster than trying to render the contents of the current view into a bitmap image yourself.
If you want to apply a graphical effect, such as blur, to a snapshot, use the drawViewHierarchyInRect:afterScreenUpdates:
method instead.
The formula for the number of binary bits required to store n integers (for example, 0 to n - 1) is:
and round up.
For example, for values -128 to 127 (signed byte) or 0 to 255 (unsigned byte), the number of integers is 256, so n is 256, giving 8 from the above formula.
For 0 to n, use n + 1 in the above formula (there are n + 1 integers).
On your calculator, loge may just be labelled log or ln (natural logarithm).
This is one way to do it:
SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
2 /
Type created
SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
2 BEGIN
3 FOR i IN 1..t_in.count LOOP
4 dbms_output.put_line(t_in(i));
5 END LOOP;
6 END;
7 /
Procedure created
SQL> DECLARE
2 v_t MyType;
3 BEGIN
4 v_t := MyType();
5 v_t.EXTEND(10);
6 v_t(1) := 'this is a test';
7 v_t(2) := 'A second test line';
8 testing(v_t);
9 END;
10 /
this is a test
A second test line
To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:
SQL> CREATE OR REPLACE PACKAGE p IS
2 TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
3
4 PROCEDURE pp (inp p_type);
5 END p;
6 /
Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
2 PROCEDURE pp (inp p_type) IS
3 BEGIN
4 FOR i IN 1..inp.count LOOP
5 dbms_output.put_line(inp(i));
6 END LOOP;
7 END pp;
8 END p;
9 /
Package body created
SQL> DECLARE
2 v_t p.p_type;
3 BEGIN
4 v_t(1) := 'this is a test of p';
5 v_t(2) := 'A second test line for p';
6 p.pp(v_t);
7 END;
8 /
this is a test of p
A second test line for p
PL/SQL procedure successfully completed
SQL>
This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.
You can get id through below Code...Its Simple and Fast
<?php $post_id = get_the_ID();
echo $post_id;
?>
This worked for me-
if(Mage::registry('current_product')->getTypeId() == 'simple' ) {
Use getTypeId()
org.apache.commons.lang3.StringUtils.substring(s, -7)
gives you the answer. It returns the input if it is shorter than 7, and null if s == null. It never throws an exception.
rsync
include exclude pattern examples:
"*" means everything
"dir1" transfers empty directory [dir1]
"dir*" transfers empty directories like: "dir1", "dir2", "dir3", etc...
"file*" transfers files whose names start with [file]
"dir**" transfers every path that starts with [dir] like "dir1/file.txt", "dir2/bar/ffaa.html", etc...
"dir***" same as above
"dir1/*" does nothing
"dir1/**" does nothing
"dir1/***" transfers [dir1] directory and all its contents like "dir1/file.txt", "dir1/fooo.sh", "dir1/fold/baar.py", etc...
And final note is that simply dont rely on asterisks that are used in the beginning for evaluating paths; like "**dir"
(its ok to use them for single folders or files but not paths) and note that more than two asterisks dont work for file names.
For converting date to string check this thread
Convert java.util.Date to String
And for converting string to date try this,
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class StringToDate
{
public static void main(String[] args) throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
String strDate = "14/03/2003 08:05:10";
System.out.println("Date - " + sdf.parse(strDate));
}
}
return value in array
$data = json_decode(file_get_contents('php://input'), true);
char source[1000000];
FILE *fp = fopen("TheFile.txt", "r");
if(fp != NULL)
{
while((symbol = getc(fp)) != EOF)
{
strcat(source, &symbol);
}
fclose(fp);
}
There are quite a few things wrong with this code:
sizeof(source)
, this is prone to buffer overflows.The
strcat()
function appends a copy of the null-terminated string s2 to the end of the null-terminated string s1, then add a terminating `\0'.
You are appending a character (not a NUL-terminated string!) to a string that may or may not be NUL-terminated. The only time I can imagine this working according to the man-page description is if every character in the file is NUL-terminated, in which case this would be rather pointless. So yes, this is most definitely a terrible abuse of strcat()
.
The following are two alternatives to consider using instead.
If you know the maximum buffer size ahead of time:
#include <stdio.h>
#define MAXBUFLEN 1000000
char source[MAXBUFLEN + 1];
FILE *fp = fopen("foo.txt", "r");
if (fp != NULL) {
size_t newLen = fread(source, sizeof(char), MAXBUFLEN, fp);
if ( ferror( fp ) != 0 ) {
fputs("Error reading file", stderr);
} else {
source[newLen++] = '\0'; /* Just to be safe. */
}
fclose(fp);
}
Or, if you do not:
#include <stdio.h>
#include <stdlib.h>
char *source = NULL;
FILE *fp = fopen("foo.txt", "r");
if (fp != NULL) {
/* Go to the end of the file. */
if (fseek(fp, 0L, SEEK_END) == 0) {
/* Get the size of the file. */
long bufsize = ftell(fp);
if (bufsize == -1) { /* Error */ }
/* Allocate our buffer to that size. */
source = malloc(sizeof(char) * (bufsize + 1));
/* Go back to the start of the file. */
if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ }
/* Read the entire file into memory. */
size_t newLen = fread(source, sizeof(char), bufsize, fp);
if ( ferror( fp ) != 0 ) {
fputs("Error reading file", stderr);
} else {
source[newLen++] = '\0'; /* Just to be safe. */
}
}
fclose(fp);
}
free(source); /* Don't forget to call free() later! */
Algorithm MaxMin(first, last, max, min)
//This algorithm stores the highest and lowest element
//Values of the global array A in the global variables max and min
//tmax and tmin are temporary global variables
{
if (first==last) //Sub-array contains single element
{
max=A[first];
min=A[first];
}
else if(first+1==last) //Sub-array contains two elements
{
if(A[first]<A[Last])
{
max=a[last]; //Second element is largest
min=a[first]; //First element is smallest
}
else
{
max=a[first]; //First element is Largest
min=a[last]; //Second element is smallest
}
}
else
//sub-array contains more than two elements
{
//Hence partition the sub-array into smaller sub-array
mid=(first+last)/2;
//Recursively solve the sub-array
MaxMin(first,mid,max,min);
MaxMin(mid+1,last,tmax,tmin);
if(max<tmax)
{
max=tmax;
}
if(min>tmin)
{
min=tmin;
}
}
}
Not available any more, https://support.google.com/drive/answer/2881970?hl=en
Host web pages with Google Drive
Note: This feature will not be available after August 31, 2016.
I highly recommend https://www.heroku.com/ and https://www.netlify.com/
A little bit more expanded than list comprehension but likewise useful:
def str_list_to_int_list(str_list):
n = 0
while n < len(str_list):
str_list[n] = int(str_list[n])
n += 1
return(str_list)
e.g.
>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]
Also:
def str_list_to_int_list(str_list):
int_list = [int(n) for n in str_list]
return int_list
I guess this is also possible like this?
var movies = _db.Movies.TakeWhile(p => p.Genres.Any(x => listOfGenres.Contains(x));
Is "TakeWhile" worse than "Where" in sense of performance or clarity?
just use ( to make it in the center of your layout)
android:layout_gravity="center"
and use
android:layout_marginBottom="80dp"
android:layout_marginTop="80dp"
to change postion
If you want to split a dataframe according to values of some variable, I'd suggest using daply()
from the plyr
package.
library(plyr)
x <- daply(df, .(splitting_variable), function(x)return(x))
Now, x
is an array of dataframes. To access one of the dataframes, you can index it with the name of the level of the splitting variable.
x$Level1
#or
x[["Level1"]]
I'd be sure that there aren't other more clever ways to deal with your data before splitting it up into many dataframes though.
You should set default values in migrations:
$table->tinyInteger('role')->default(1);
This piece of code will help you better solve your problem, as we cannot specify width directly to the RaisedButton, we can specify the width to it's child
double width = MediaQuery.of(context).size.width;
var maxWidthChild = SizedBox(
width: width,
child: Text(
StringConfig.acceptButton,
textAlign: TextAlign.center,
));
RaisedButton(
child: maxWidthChild,
onPressed: (){},
color: Colors.white,
);
Building on what was done earlier by the accepted answer, if you would like to have it recursive.
class FullStruct:
def __init__(self, **kwargs):
for key, value in kwargs.items():
if isinstance(value, dict):
f = FullStruct(**value)
self.__dict__.update({key: f})
else:
self.__dict__.update({key: value})
Considering there might be several img
tags I would recommend re.findall
:
import re
with open("sample.txt", 'r') as f_in, open('writetest.txt', 'w') as f_out:
for line in f_in:
for img in re.findall('<img[^>]+>', line):
print >> f_out, "yo it's a {}".format(img)
So, if you are using flask_restful
Package for API's
returning 201 would becomes like
def bla(*args, **kwargs):
...
return data, 201
where data
should be any hashable/ JsonSerialiable value, like dict, string.
[Ljava.lang.Object;
is the name for Object[].class
, the java.lang.Class
representing the class of array of Object
.
The naming scheme is documented in Class.getName()
:
If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).
If this class object represents a primitive type or
void
, then the name returned is the Java language keyword corresponding to the primitive type orvoid
.If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more
'['
characters representing the depth of the array nesting. The encoding of element type names is as follows:Element Type Encoding boolean Z byte B char C double D float F int I long J short S class or interface Lclassname;
Yours is the last on that list. Here are some examples:
// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx
The reason why the toString()
method on arrays returns String
in this format is because arrays do not @Override
the method inherited from Object
, which is specified as follows:
The
toString
method for classObject
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:getClass().getName() + '@' + Integer.toHexString(hashCode())
Note: you can not rely on the toString()
of any arbitrary object to follow the above specification, since they can (and usually do) @Override
it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass()
on it (a final
method inherited from Object
) and then reflecting on the returned Class
object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).
toString
for arraysjava.util.Arrays
provides toString
overloads for primitive arrays and Object[]
. There is also deepToString
that you may want to use for nested arrays.
Here are some examples:
int[] nums = { 1, 2, 3 };
System.out.println(nums);
// [I@xxxxx
System.out.println(Arrays.toString(nums));
// [1, 2, 3]
int[][] table = {
{ 1, },
{ 2, 3, },
{ 4, 5, 6, },
};
System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]
System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]
There are also Arrays.equals
and Arrays.deepEquals
that perform array equality comparison by their elements, among many other array-related utility methods.
in the file .eslintrc.json in side roles add this code it will solve this issue
"rules": {
"prettier/prettier": ["error",{
"endOfLine": "auto"}
]
}
You can use below code:
<video width="400" controls autoplay>
<source src="D:/mov1.mov" type="video/mp4">
</video>
this code will help you.
In my project I managed to use GridLayout and results are very stable, with no flickering and with a perfectly working vertical scrollbar.
First I created a JPanel for the settings; in my case it is a grid with a row for each parameter and two columns: left column is for labels and right column is for components. I believe your case is similar.
JPanel yourSettingsPanel = new JPanel();
yourSettingsPanel.setLayout(new GridLayout(numberOfParams, 2));
I then populate this panel by iterating on my parameters and alternating between adding a JLabel and adding a component.
for (int i = 0; i < numberOfParams; ++i) {
yourSettingsPanel.add(labels[i]);
yourSettingsPanel.add(components[i]);
}
To prevent yourSettingsPanel from extending to the entire container I first wrap it in the north region of a dummy panel, that I called northOnlyPanel.
JPanel northOnlyPanel = new JPanel();
northOnlyPanel.setLayout(new BorderLayout());
northOnlyPanel.add(yourSettingsPanel, BorderLayout.NORTH);
Finally I wrap the northOnlyPanel in a JScrollPane, which should behave nicely pretty much anywhere.
JScrollPane scroll = new JScrollPane(northOnlyPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Most likely you want to display this JScrollPane extended inside a JFrame; you can add it to a BorderLayout JFrame, in the CENTER region:
window.add(scroll, BorderLayout.CENTER);
In my case I put it on the left column of a GridLayout(1, 2) panel, and I use the right column to display contextual help for each parameter.
JTextArea help = new JTextArea();
help.setLineWrap(true);
help.setWrapStyleWord(true);
help.setEditable(false);
JPanel split = new JPanel();
split.setLayout(new GridLayout(1, 2));
split.add(scroll);
split.add(help);
I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();
it gives back an array of ids [50,2,3]
and this is the whole query I used:
$article_tags = DB::table('tags')
->join('taggables', function ($join) use ($id) {
$join->on('tags.id', '=', 'taggables.tag_id');
$join->where([
['taggable_id', '=', $id],
['taggable_type','=','article']
]);
})->select('tags.id')->get()->pluck('id')->toArray();
I've encountered the same problem in OSX.
I've tried to replace the things like
$cfg['Servers'][$i]['usergroups'] to $cfg['Servers'][$i]['pma__usergroups']
...
It works in safari but still fails in chrome.
But the so called 'work' in safari can get the message that the features which have been modified are not in effect at all.
However, the 'work' means that I can access the dbs listed left.
I think this problem maybe a bug in the new version of XAMPP, since the #1932 problems in google is new and boomed.
You can have a try at an older version of XAMPP instead until the bug is solved.
http://sourceforge.net/projects/xampp/files/XAMPP%20Linux/5.6.12/
Hope it can help you.
It seems that this is not an uncommon problem.
Check this first.
If that doesn't help, you can install a local DNS server on Windows, such as this. Configure Windows to use localhost as the DNS server. This server can be configured to be authoritative for whatever fake domains you need, and to forward requests on to the real DNS servers for all other requests.
I personally think this is a bit over the top, and can't see why the hosts file wouldn't work. But it should solve the problem you're having. Make sure you set up your normal DNS servers as forwarders as well.
The following example using the iris dataset works fine:
dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
id.vars = "Species")
ggplot(aes(x = 1:nrow(iris), y = value, color = variable), data = dat) +
geom_point() + geom_line()
Try this:
System.Windows.Forms.MessageBox.Show("Here's a message!");
Any other places you use TimerEventProcessor or Counter?
Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.
So instead of _Counter, you should use:
// when starting the timer:
DateTime _started = DateTime.UtcNow;
// in TimerEventProcessor:
seconds = (DateTime.UtcNow-started).TotalSeconds;
Label.Text = seconds.ToString();
Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.
if your signal is in the matrix X
, you make it zero-mean by removing the average:
X=X-mean(X(:));
and unit variance by dividing by the standard deviation:
X=X/std(X(:));
I saw this error
Only local connections are allowed
And I updated both the selenium webdriver, and the google-chrome-stable
package
webdriver-manager update
zypper install google-chrome-stable
This site reports the latest version of the chrome driver https://sites.google.com/a/chromium.org/chromedriver/
My working versions are chromedriver 2.41 and google-chrome-stable 68
HTTP sends bytes. If the resource in question is text, the character encoding is normally specified, either by the Content-Type HTTP header or by another mechanism (an RFC, HTML meta http-equiv
,...).
urllib
should know how to encode the bytes to a string, but it's too naïve—it's a horribly underpowered and un-Pythonic library.
Dive Into Python 3 provides an overview about the situation.
Your "work-around" is fine—although it feels wrong, it's the correct way to do it.
I've found none of the suggestions to really work. Here's a more robust one that normalizes spacing when finding classes.
//Inside closure so that the inner functions don't need regeneration on every call.
const getCssClasses = (function () {
function normalize(str) {
if (!str) return '';
str = String(str).replace(/\s*([>~+])\s*/g, ' $1 '); //Normalize symbol spacing.
return str.replace(/(\s+)/g, ' ').trim(); //Normalize whitespace
}
function split(str, on) { //Split, Trim, and remove empty elements
return str.split(on).map(x => x.trim()).filter(x => x);
}
function containsAny(selText, ors) {
return selText ? ors.some(x => selText.indexOf(x) >= 0) : false;
}
return function (selector) {
const logicalORs = split(normalize(selector), ',');
const sheets = Array.from(window.document.styleSheets);
const ruleArrays = sheets.map((x) => Array.from(x.rules || x.cssRules || []));
const allRules = ruleArrays.reduce((all, x) => all.concat(x), []);
return allRules.filter((x) => containsAny(normalize(x.selectorText), logicalORs));
};
})();
Here's it in action from the Chrome console.
This is quite frustrating, but it's a containment issue (the .svn folders keep track also of ignored files). Any item that needs to be ignored is to be added to the ignore list of the immediate parent folder.
So, I had a new sub-folder with a new file in it and wanted to ignore that file but I couldn't do it because the option was grayed out. I solved it by committing the new folder first, which I wanted to (it was a cache folder), and then adding that file to the ignore list (of the newly added folder ;-), having the chance to add a pattern instead of a single file.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("223232-1.jpg".GetUntilOrEmpty());
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
Console.WriteLine("34443553-5.jpg".GetUntilOrEmpty());
Console.ReadKey();
}
}
static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
if (!String.IsNullOrWhiteSpace(text))
{
int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal);
if (charLocation > 0)
{
return text.Substring(0, charLocation);
}
}
return String.Empty;
}
}
Results:
223232
443
34443553
344
34
To also handle floating point numbers:
(Older) JavaScript:
var arr = ["20.0","40.1","80.2","400.3"],
n = arr.length,
sum = 0;
while(n--)
sum += parseFloat(arr[n]) || 0;
ECMA 5.1/6:
var arr = ["20.0","40.1","80.2","400.3"],
sum = 0;
arr.forEach(function(num){sum+=parseFloat(num) || 0;});
ES6:
var sum = ["20.0","40.1","80.2","400.3"].reduce((pv,cv)=>{
return pv + (parseFloat(cv)||0);
},0);
The reduce() is available in older ECMAScript versions, the arrow function is what makes this ES6-specific.
I'm passing in 0 as the first pv
value, so I don't need parseFloat around it — it'll always hold the previous sum, which will always be numeric. Because the current value, cv
, can be non-numeric (NaN
), we use ||0
on it to skip that value in the array. This is terrific if you want to break up a sentence and get the sum of the numbers in it. Here's a more detailed example:
let num_of_fruits = `
This is a sentence where 1.25 values are oranges
and 2.5 values are apples. How many fruits are
there?
`.split(/\s/g).reduce((p,c)=>p+(parseFloat(c)||0), 0);
// num_of_fruits == 3.75
jQuery:
var arr = ["20.0","40.1","80.2","400.3"],
sum = 0;
$.each(arr,function(){sum+=parseFloat(this) || 0;});
What the above gets you:
123
or "123"
), floating point string or number ("123.4"
or 123.4
), or even text (abc
)I took @hajamie's solution and wrapped it up into a slightly more convenient script wrapper.
I added an option to start from an offset before the end of the file, so you can use the tail-like functionality of reading a certain amount from the end of the file. Note the offset is in bytes, not lines.
There's also an option to continue waiting for more content.
Examples (assuming you save this as TailFile.ps1):
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000 -Follow:$true
.\TailFile.ps1 -File .\path\to\myfile.log -Follow:$true
And here is the script itself...
param (
[Parameter(Mandatory=$true,HelpMessage="Enter the path to a file to tail")][string]$File = "",
[Parameter(Mandatory=$true,HelpMessage="Enter the number of bytes from the end of the file")][int]$InitialOffset = 10248,
[Parameter(Mandatory=$false,HelpMessage="Continuing monitoring the file for new additions?")][boolean]$Follow = $false
)
$ci = get-childitem $File
$fullName = $ci.FullName
$reader = new-object System.IO.StreamReader(New-Object IO.FileStream($fullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
#start at the end of the file
$lastMaxOffset = $reader.BaseStream.Length - $InitialOffset
while ($true)
{
#if the file size has not changed, idle
if ($reader.BaseStream.Length -ge $lastMaxOffset) {
#seek to the last max offset
$reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null
#read out of the file until the EOF
$line = ""
while (($line = $reader.ReadLine()) -ne $null) {
write-output $line
}
#update the last max offset
$lastMaxOffset = $reader.BaseStream.Position
}
if($Follow){
Start-Sleep -m 100
} else {
break;
}
}
Strings do have a length method: __len__()
The protocol in Python is to implement this method on objects which have a length and use the built-in len()
function, which calls it for you, similar to the way you would implement __iter__()
and use the built-in iter()
function (or have the method called behind the scenes for you) on objects which are iterable.
See Emulating container types for more information.
Here's a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment
Not possible in just grep I believe
for sed:
name=`echo $f | sed -E 's/([0-9]+_([a-z]+)_[0-9a-z]*)|.*/\2/'`
I'll take a stab at the bonus though:
echo "$name.jpg"
I may suggest NOT looping over each rows EACH time CellFormating is called, because it is called everytime A SINGLE ROW need to be refreshed.
Private Sub dgv_DisplayData_Vertical_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgv_DisplayData_Vertical.CellFormatting
Try
If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "6" Then
e.CellStyle.BackColor = Color.DimGray
End If
If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "5" Then
e.CellStyle.BackColor = Color.DarkSlateGray
End If
If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "4" Then
e.CellStyle.BackColor = Color.SlateGray
End If
If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "3" Then
e.CellStyle.BackColor = Color.LightGray
End If
If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "0" Then
e.CellStyle.BackColor = Color.White
End If
Catch ex As Exception
End Try
End Sub
Go to Xcode preferences by clicking on "Xcode" in the left hand side upper corner.
Select "Text Editing".
Select "Show: Line numbers" and click on check box for enable it.
Close it.
Then you will see the line number in Xcode.
I think that, we don't need parse the JSON object into a string, if the remote server accepts json into they request, just run:
const request = await fetch ('/echo/json', {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: { a: 1, b: 2 }
});
Such as the curl request
curl -v -X POST -H 'Content-Type: application/json' -d '@data.json' '/echo/json'
In case to the remote serve not accept a json file as the body, just send a dataForm:
const data = new FormData ();
data.append ('a', 1);
data.append ('b', 2);
const request = await fetch ('/echo/form', {
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',
body: data
});
Such as the curl request
curl -v -X POST -H 'Content-type: application/x-www-form-urlencoded' -d '@data.txt' '/echo/form'
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
I have posted a very simple method to install OpenCV 2.4 for Python in Windows here : Install OpenCV in Windows for Python
It is just as simple as copy and paste. Hope it will be useful for future viewers.
Download Python, Numpy, OpenCV from their official sites.
Extract OpenCV (will be extracted to a folder opencv)
Copy ..\opencv\build\python\x86\2.7\cv2.pyd
Paste it in C:\Python27\Lib\site-packages
Open Python IDLE or terminal, and type
>>> import cv2
If no errors shown, it is OK.
UPDATE (Thanks to dana for this info):
If you are using the VideoCapture feature, you must copy opencv_ffmpeg.dll
into your path as well. See: https://stackoverflow.com/a/11703998/1134940
I've always understood that the below will give me the fastest response times.
SELECT COUNT(1) FROM ... WHERE ...
You can prefer quick-json parser to meet your requirement...
quick-json parser is very straight forward, flexible, very fast and customizable. Try this out
[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -
Compliant with JSON specification (RFC4627)
High-Performance JSON parser
Supports Flexible/Configurable parsing approach
Configurable validation of key/value pairs of any JSON Heirarchy
Easy to use # Very Less foot print
Raises developer friendly and easy to trace exceptions
Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered
Validating and Non-Validating parser support
Support for two types of configuration (JSON/XML) for using quick-json validating parser
Require JDK 1.5 # No dependency on external libraries
Support for Json Generation through object serialization
Support for collection type selection during parsing process
For e.g.
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
Camel is a framework with a consistent API and programming model for integrating applications together. The API is based on theories in Enterprise Integration Patterns - i.e., bunch of design patterns that tend to use messaging. It provides out of the box implementations of most of these patterns, and additionally ships with over 200 different components you can use to easily talk to all kinds of other systems. To use Camel, first write your business logic in POJOs and implement simple interfaces centered around messages. Then use Camel’s DSL to create "Routes" which are sets of rules for gluing your application together.
On the surface, Camel's functionality rivals traditional Enterprise Service Bus products. We typically think of a Camel Route being a "mediation" (aka orchestration) component that lives on the server side, but because it's a Java library it’s easy to embed and it can live on a client side app just as well and help you integrate it with point to point services (aka choreography). You can even take your POJOs that process the messages inside the Camel route and easily spin them off into their own remote consumer processes, e.g. if you needed to scale just one piece independently. You can use Camel to connect routes or processors through any number of different remote transport/protocols depending on your needs. Do you need an extremely efficient and fast binary protocol, or one that is more human readable and easy to debug? What if you wanted to switch? With Camel this is usually as easy as changing a line or two in your route and not changing any business logic at all. Or you could support both - you’re free to run many Routes at once in a Camel Context.
You don't really need to use Camel for simple applications that are going to live in a single process or JVM - it would be overkill. But it's not conceptually any more difficult than code you may write yourself. And if your requirements change, the separation of business logic and glue code makes it easier to maintain over time. Once you learn the Camel API, it is easy to use it like a Swiss-Army knife and apply it quickly in many different contexts to cut down on the amount of custom code you’d otherwise have to write. You can learn one flavor - the Java DSL, for example, a fluent API that's easy to chain together - and pick up the other flavors easily.
Overall Camel is a great fit if you are trying to do microservices. I have found it invaluable for evolutionary architecture, because you can put off a lot of the difficult, "easy-to-get-wrong" decisions about protocols, transports and other system integration problems until you know more about your problem domain. Just focus on your EIPs and core business logic and switch to new Routes with the "right" components as you learn more.
You can find your maven files here:
cd ~/.m2
Probably you need to copy settings.xml in your .m2
folder:
cp /usr/local/bin/apache-maven-2.2.1/conf/settings.xml .m2/
If no .m2 folder exists:
mkdir -p ~/.m2
I think to get a complete answer, people have to know how enums work internally in .NET.
How stuff works
An enum in .NET is a structure that maps a set of values (fields) to a basic type (the default is int
). However, you can actually choose the integral type that your enum maps to:
public enum Foo : short
In this case the enum is mapped to the short
data type, which means it will be stored in memory as a short and will behave as a short when you cast and use it.
If you look at it from a IL point of view, a (normal, int) enum looks like this:
.class public auto ansi serializable sealed BarFlag extends System.Enum
{
.custom instance void System.FlagsAttribute::.ctor()
.custom instance void ComVisibleAttribute::.ctor(bool) = { bool(true) }
.field public static literal valuetype BarFlag AllFlags = int32(0x3fff)
.field public static literal valuetype BarFlag Foo1 = int32(1)
.field public static literal valuetype BarFlag Foo2 = int32(0x2000)
// and so on for all flags or enum values
.field public specialname rtspecialname int32 value__
}
What should get your attention here is that the value__
is stored separately from the enum values. In the case of the enum Foo
above, the type of value__
is int16. This basically means that you can store whatever you want in an enum, as long as the types match.
At this point I'd like to point out that System.Enum
is a value type, which basically means that BarFlag
will take up 4 bytes in memory and Foo
will take up 2 -- e.g. the size of the underlying type (it's actually more complicated than that, but hey...).
The answer
So, if you have an integer that you want to map to an enum, the runtime only has to do 2 things: copy the 4 bytes and name it something else (the name of the enum). Copying is implicit because the data is stored as value type - this basically means that if you use unmanaged code, you can simply interchange enums and integers without copying data.
To make it safe, I think it's a best practice to know that the underlying types are the same or implicitly convertible and to ensure the enum values exist (they aren't checked by default!).
To see how this works, try the following code:
public enum MyEnum : int
{
Foo = 1,
Bar = 2,
Mek = 5
}
static void Main(string[] args)
{
var e1 = (MyEnum)5;
var e2 = (MyEnum)6;
Console.WriteLine("{0} {1}", e1, e2);
Console.ReadLine();
}
Note that casting to e2
also works! From the compiler perspective above this makes sense: the value__
field is simply filled with either 5 or 6 and when Console.WriteLine
calls ToString()
, the name of e1
is resolved while the name of e2
is not.
If that's not what you intended, use Enum.IsDefined(typeof(MyEnum), 6)
to check if the value you are casting maps to a defined enum.
Also note that I'm explicit about the underlying type of the enum, even though the compiler actually checks this. I'm doing this to ensure I don't run into any surprises down the road. To see these surprises in action, you can use the following code (actually I've seen this happen a lot in database code):
public enum MyEnum : short
{
Mek = 5
}
static void Main(string[] args)
{
var e1 = (MyEnum)32769; // will not compile, out of bounds for a short
object o = 5;
var e2 = (MyEnum)o; // will throw at runtime, because o is of type int
Console.WriteLine("{0} {1}", e1, e2);
Console.ReadLine();
}
For people who searched for php multidimensional array get values
and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach
, which is array_column
For example, if I only want to get hotel_name
from the below array, and form to another array:
$hotels = [
[
'hotel_name' => 'Hotel A',
'info' => 'Hotel A Info',
],
[
'hotel_name' => 'Hotel B',
'info' => 'Hotel B Info',
]
];
I can do this using array_column
:
$hotel_name = array_column($hotels, 'hotel_name');
print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']
For the actual answer for this question, it can also be beautified by array_column
and call_user_func_array('array_merge', $twoDimensionalArray);
Let's make the data in PHP:
$hotels = [
[
'hotel_name' => 'Hotel A',
'info' => 'Hotel A Info',
'rooms' => [
[
'room_name' => 'Luxury Room',
'bed' => 2,
'boards' => [
'board_id' => 1,
'price' => 200
]
],
[
'room_name' => 'Non Luxy Room',
'bed' => 4,
'boards' => [
'board_id' => 2,
'price' => 150
]
],
]
],
[
'hotel_name' => 'Hotel B',
'info' => 'Hotel B Info',
'rooms' => [
[
'room_name' => 'Luxury Room',
'bed' => 2,
'boards' => [
'board_id' => 3,
'price' => 900
]
],
[
'room_name' => 'Non Luxy Room',
'bed' => 4,
'boards' => [
'board_id' => 4,
'price' => 300
]
],
]
]
];
And here's the calculation:
$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');
foreach($boards as $board){
$board_id = $board['board_id'];
$price = $board['price'];
echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}
Which will give you the following result:
Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300
In addition to all the previous answers, I would like to tell about the different behavior of gather()
and wait()
in case they are cancelled.
If gather()
is cancelled, all submitted awaitables (that have not completed yet) are also cancelled.
If the wait()
task is cancelled, it simply throws an CancelledError
and the waited tasks remain intact.
Simple example:
import asyncio
async def task(arg):
await asyncio.sleep(5)
return arg
async def cancel_waiting_task(work_task, waiting_task):
await asyncio.sleep(2)
waiting_task.cancel()
try:
await waiting_task
print("Waiting done")
except asyncio.CancelledError:
print("Waiting task cancelled")
try:
res = await work_task
print(f"Work result: {res}")
except asyncio.CancelledError:
print("Work task cancelled")
async def main():
work_task = asyncio.create_task(task("done"))
waiting = asyncio.create_task(asyncio.wait({work_task}))
await cancel_waiting_task(work_task, waiting)
work_task = asyncio.create_task(task("done"))
waiting = asyncio.gather(work_task)
await cancel_waiting_task(work_task, waiting)
asyncio.run(main())
Output:
asyncio.wait()
Waiting task cancelled
Work result: done
----------------
asyncio.gather()
Waiting task cancelled
Work task cancelled
Sometimes it becomes necessary to combine wait()
and gather()
functionality. For example, we want to wait for the completion of at least one task and cancel the rest pending tasks after that, and if the waiting
itself was canceled, then also cancel all pending tasks.
As real examples, let's say we have a disconnect event and a work task. And we want to wait for the results of the work task, but if the connection was lost, then cancel it. Or we will make several parallel requests, but upon completion of at least one response, cancel all others.
It could be done this way:
import asyncio
from typing import Optional, Tuple, Set
async def wait_any(
tasks: Set[asyncio.Future], *, timeout: Optional[int] = None,
) -> Tuple[Set[asyncio.Future], Set[asyncio.Future]]:
tasks_to_cancel: Set[asyncio.Future] = set()
try:
done, tasks_to_cancel = await asyncio.wait(
tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED
)
return done, tasks_to_cancel
except asyncio.CancelledError:
tasks_to_cancel = tasks
raise
finally:
for task in tasks_to_cancel:
task.cancel()
async def task():
await asyncio.sleep(5)
async def cancel_waiting_task(work_task, waiting_task):
await asyncio.sleep(2)
waiting_task.cancel()
try:
await waiting_task
print("Waiting done")
except asyncio.CancelledError:
print("Waiting task cancelled")
try:
res = await work_task
print(f"Work result: {res}")
except asyncio.CancelledError:
print("Work task cancelled")
async def check_tasks(waiting_task, working_task, waiting_conn_lost_task):
try:
await waiting_task
print("waiting is done")
except asyncio.CancelledError:
print("waiting is cancelled")
try:
await waiting_conn_lost_task
print("connection is lost")
except asyncio.CancelledError:
print("waiting connection lost is cancelled")
try:
await working_task
print("work is done")
except asyncio.CancelledError:
print("work is cancelled")
async def work_done_case():
working_task = asyncio.create_task(task())
connection_lost_event = asyncio.Event()
waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
await check_tasks(waiting_task, working_task, waiting_conn_lost_task)
async def conn_lost_case():
working_task = asyncio.create_task(task())
connection_lost_event = asyncio.Event()
waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
await asyncio.sleep(2)
connection_lost_event.set() # <---
await check_tasks(waiting_task, working_task, waiting_conn_lost_task)
async def cancel_waiting_case():
working_task = asyncio.create_task(task())
connection_lost_event = asyncio.Event()
waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
await asyncio.sleep(2)
waiting_task.cancel() # <---
await check_tasks(waiting_task, working_task, waiting_conn_lost_task)
async def main():
print("Work done")
print("-------------------")
await work_done_case()
print("\nConnection lost")
print("-------------------")
await conn_lost_case()
print("\nCancel waiting")
print("-------------------")
await cancel_waiting_case()
asyncio.run(main())
Output:
Work done
-------------------
waiting is done
waiting connection lost is cancelled
work is done
Connection lost
-------------------
waiting is done
connection is lost
work is cancelled
Cancel waiting
-------------------
waiting is cancelled
waiting connection lost is cancelled
work is cancelled
The ASPX code will look something like this:
<asp:RadioButtonList ID="rblist1" runat="server">
<asp:ListItem Text ="Item1" Value="1" />
<asp:ListItem Text ="Item2" Value="2" />
<asp:ListItem Text ="Item3" Value="3" />
<asp:ListItem Text ="Item4" Value="4" />
</asp:RadioButtonList>
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />
And the code behind:
protected void Button1_Click(object sender, EventArgs e)
{
string selectedValue = rblist1.SelectedValue;
Response.Write(selectedValue);
}
Always have handy the un-minified CSS for bootstrap so you can see what styles they have on their components, then create a CSS file AFTER it, if you don't use LESS and over-write their mixins or whatever
This is the default modal css for 768px and up:
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
...
}
They have a class modal-lg
for larger widths
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
If you need something twice the 600px size, and something fluid, do something like this in your CSS after the Bootstrap css and assign that class to the modal-dialog.
@media (min-width: 768px) {
.modal-xl {
width: 90%;
max-width:1200px;
}
}
HTML
<div class="modal-dialog modal-xl">
Demo: http://jsbin.com/yefas/1
The wb
indicates that the file is opened for writing in binary mode.
When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b
is excluded as in just w
or when you specify text mode with wt
), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n
) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe
or png
file.
Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.
References:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open
If column is not NOT NULL
(nullable).
You just put NULL
instead of value in INSERT
statement.
And if you don't want R to add decimals or zeros, you can stop it from drawing the x axis or the y axis or both using ...axt. Then, you can add your own ticks and labels:
plot(x, y, xaxt="n")
plot(x, y, yaxt="n")
axis(1 or 2, at=c(1, 5, 10), labels=c("First", "Second", "Third"))
Warning: if you want to load the 'monkey patch' or 'open class' from your 'lib' folder, don't use the 'autoload' approach!!!
"config.autoload_paths" approach: only works if you are loading a class that defined only in ONE place. If some class has been already defined somewhere else, then you can't load it again by this approach.
"config/initializer/load_rb_file.rb" approach: always works! whatever the target class is a new class or an "open class" or "monkey patch" for existing class, it always works!
For more details , see: https://stackoverflow.com/a/6797707/445908
It's really simple, just download the latest toolkit from Codeplex and add the extracted AjaxControlToolkit.dll
to your toolbox in Visual Studio by right clicking the toolbox and selecting 'choose items'. You will then have the controls in your Visual STudio toolbox and using them is just a matter of dragging and dropping them onto your form, of course don't forget to add a asp:ScriptManager
to every page that uses controls from the toolkit, or optionally include it in your master page only and your content pages will inherit the script manager.
false|tee fileToTruncate
may work as well
A little bug with indexcolumn in alexander's answer: We need to take care of "not found" column:
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
int foundIndex=-1;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
{
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
{
foundIndex=columnIndex;
break;
}
}
columnIndex++; // keep adding 1 while we don't have the correct name
}
return foundIndex;
}
and
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "myDataField");
if( index>0)
{
string columnValue = e.Row.Cells[index].Text;
}
}
}
There's an error in the pattern of your SimpleDateFormat. it should be
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
You are very close.
You applied the round to the series of values given by df.value1
.
The return type is thus a Series.
You need to assign that series back to the dataframe (or another dataframe with the same Index).
Also, there is a pandas.Series.round
method which is basically a short hand for pandas.Series.apply(np.round)
.
In[2]:
df.value1 = df.value1.round()
print df
Out[2]:
item value1 value2
0 a 1 1.3
1 a 2 2.5
2 a 0 0.0
3 b 3 -1.0
4 b 5 -1.0
Have you tried setting the li width to, say, 16% with a margin of 0.5%?
nav li {
line-height: 87px;
float: left;
text-align: center;
width: 16%;
margin-right: 0.5%;
}
edit: I would set the UL to 100% width:
nav ul { width: 100%; margin: 0 auto; }
For the case of a left join with a 0..*:0..1
cardinality or a right join with a 0..1:0..*
cardinality it is possible to assign in-place the unilateral columns from the joiner (the 0..1
table) directly onto the joinee (the 0..*
table), and thereby avoid the creation of an entirely new table of data. This requires matching the key columns from the joinee into the joiner and indexing+ordering the joiner's rows accordingly for the assignment.
If the key is a single column, then we can use a single call to match()
to do the matching. This is the case I'll cover in this answer.
Here's an example based on the OP, except I've added an extra row to df2
with an id of 7 to test the case of a non-matching key in the joiner. This is effectively df1
left join df2
:
df1 <- data.frame(CustomerId=1:6,Product=c(rep('Toaster',3L),rep('Radio',3L)));
df2 <- data.frame(CustomerId=c(2L,4L,6L,7L),State=c(rep('Alabama',2L),'Ohio','Texas'));
df1[names(df2)[-1L]] <- df2[match(df1[,1L],df2[,1L]),-1L];
df1;
## CustomerId Product State
## 1 1 Toaster <NA>
## 2 2 Toaster Alabama
## 3 3 Toaster <NA>
## 4 4 Radio Alabama
## 5 5 Radio <NA>
## 6 6 Radio Ohio
In the above I hard-coded an assumption that the key column is the first column of both input tables. I would argue that, in general, this is not an unreasonable assumption, since, if you have a data.frame with a key column, it would be strange if it had not been set up as the first column of the data.frame from the outset. And you can always reorder the columns to make it so. An advantageous consequence of this assumption is that the name of the key column does not have to be hard-coded, although I suppose it's just replacing one assumption with another. Concision is another advantage of integer indexing, as well as speed. In the benchmarks below I'll change the implementation to use string name indexing to match the competing implementations.
I think this is a particularly appropriate solution if you have several tables that you want to left join against a single large table. Repeatedly rebuilding the entire table for each merge would be unnecessary and inefficient.
On the other hand, if you need the joinee to remain unaltered through this operation for whatever reason, then this solution cannot be used, since it modifies the joinee directly. Although in that case you could simply make a copy and perform the in-place assignment(s) on the copy.
As a side note, I briefly looked into possible matching solutions for multicolumn keys. Unfortunately, the only matching solutions I found were:
match(interaction(df1$a,df1$b),interaction(df2$a,df2$b))
, or the same idea with paste()
.outer(df1$a,df2$a,`==`) & outer(df1$b,df2$b,`==`)
.merge()
and equivalent package-based merge functions, which always allocate a new table to return the merged result, and thus are not suitable for an in-place assignment-based solution.For example, see Matching multiple columns on different data frames and getting other column as result, match two columns with two other columns, Matching on multiple columns, and the dupe of this question where I originally came up with the in-place solution, Combine two data frames with different number of rows in R.
I decided to do my own benchmarking to see how the in-place assignment approach compares to the other solutions that have been offered in this question.
Testing code:
library(microbenchmark);
library(data.table);
library(sqldf);
library(plyr);
library(dplyr);
solSpecs <- list(
merge=list(testFuncs=list(
inner=function(df1,df2,key) merge(df1,df2,key),
left =function(df1,df2,key) merge(df1,df2,key,all.x=T),
right=function(df1,df2,key) merge(df1,df2,key,all.y=T),
full =function(df1,df2,key) merge(df1,df2,key,all=T)
)),
data.table.unkeyed=list(argSpec='data.table.unkeyed',testFuncs=list(
inner=function(dt1,dt2,key) dt1[dt2,on=key,nomatch=0L,allow.cartesian=T],
left =function(dt1,dt2,key) dt2[dt1,on=key,allow.cartesian=T],
right=function(dt1,dt2,key) dt1[dt2,on=key,allow.cartesian=T],
full =function(dt1,dt2,key) merge(dt1,dt2,key,all=T,allow.cartesian=T) ## calls merge.data.table()
)),
data.table.keyed=list(argSpec='data.table.keyed',testFuncs=list(
inner=function(dt1,dt2) dt1[dt2,nomatch=0L,allow.cartesian=T],
left =function(dt1,dt2) dt2[dt1,allow.cartesian=T],
right=function(dt1,dt2) dt1[dt2,allow.cartesian=T],
full =function(dt1,dt2) merge(dt1,dt2,all=T,allow.cartesian=T) ## calls merge.data.table()
)),
sqldf.unindexed=list(testFuncs=list( ## note: must pass connection=NULL to avoid running against the live DB connection, which would result in collisions with the residual tables from the last query upload
inner=function(df1,df2,key) sqldf(paste0('select * from df1 inner join df2 using(',paste(collapse=',',key),')'),connection=NULL),
left =function(df1,df2,key) sqldf(paste0('select * from df1 left join df2 using(',paste(collapse=',',key),')'),connection=NULL),
right=function(df1,df2,key) sqldf(paste0('select * from df2 left join df1 using(',paste(collapse=',',key),')'),connection=NULL) ## can't do right join proper, not yet supported; inverted left join is equivalent
##full =function(df1,df2,key) sqldf(paste0('select * from df1 full join df2 using(',paste(collapse=',',key),')'),connection=NULL) ## can't do full join proper, not yet supported; possible to hack it with a union of left joins, but too unreasonable to include in testing
)),
sqldf.indexed=list(testFuncs=list( ## important: requires an active DB connection with preindexed main.df1 and main.df2 ready to go; arguments are actually ignored
inner=function(df1,df2,key) sqldf(paste0('select * from main.df1 inner join main.df2 using(',paste(collapse=',',key),')')),
left =function(df1,df2,key) sqldf(paste0('select * from main.df1 left join main.df2 using(',paste(collapse=',',key),')')),
right=function(df1,df2,key) sqldf(paste0('select * from main.df2 left join main.df1 using(',paste(collapse=',',key),')')) ## can't do right join proper, not yet supported; inverted left join is equivalent
##full =function(df1,df2,key) sqldf(paste0('select * from main.df1 full join main.df2 using(',paste(collapse=',',key),')')) ## can't do full join proper, not yet supported; possible to hack it with a union of left joins, but too unreasonable to include in testing
)),
plyr=list(testFuncs=list(
inner=function(df1,df2,key) join(df1,df2,key,'inner'),
left =function(df1,df2,key) join(df1,df2,key,'left'),
right=function(df1,df2,key) join(df1,df2,key,'right'),
full =function(df1,df2,key) join(df1,df2,key,'full')
)),
dplyr=list(testFuncs=list(
inner=function(df1,df2,key) inner_join(df1,df2,key),
left =function(df1,df2,key) left_join(df1,df2,key),
right=function(df1,df2,key) right_join(df1,df2,key),
full =function(df1,df2,key) full_join(df1,df2,key)
)),
in.place=list(testFuncs=list(
left =function(df1,df2,key) { cns <- setdiff(names(df2),key); df1[cns] <- df2[match(df1[,key],df2[,key]),cns]; df1; },
right=function(df1,df2,key) { cns <- setdiff(names(df1),key); df2[cns] <- df1[match(df2[,key],df1[,key]),cns]; df2; }
))
);
getSolTypes <- function() names(solSpecs);
getJoinTypes <- function() unique(unlist(lapply(solSpecs,function(x) names(x$testFuncs))));
getArgSpec <- function(argSpecs,key=NULL) if (is.null(key)) argSpecs$default else argSpecs[[key]];
initSqldf <- function() {
sqldf(); ## creates sqlite connection on first run, cleans up and closes existing connection otherwise
if (exists('sqldfInitFlag',envir=globalenv(),inherits=F) && sqldfInitFlag) { ## false only on first run
sqldf(); ## creates a new connection
} else {
assign('sqldfInitFlag',T,envir=globalenv()); ## set to true for the one and only time
}; ## end if
invisible();
}; ## end initSqldf()
setUpBenchmarkCall <- function(argSpecs,joinType,solTypes=getSolTypes(),env=parent.frame()) {
## builds and returns a list of expressions suitable for passing to the list argument of microbenchmark(), and assigns variables to resolve symbol references in those expressions
callExpressions <- list();
nms <- character();
for (solType in solTypes) {
testFunc <- solSpecs[[solType]]$testFuncs[[joinType]];
if (is.null(testFunc)) next; ## this join type is not defined for this solution type
testFuncName <- paste0('tf.',solType);
assign(testFuncName,testFunc,envir=env);
argSpecKey <- solSpecs[[solType]]$argSpec;
argSpec <- getArgSpec(argSpecs,argSpecKey);
argList <- setNames(nm=names(argSpec$args),vector('list',length(argSpec$args)));
for (i in seq_along(argSpec$args)) {
argName <- paste0('tfa.',argSpecKey,i);
assign(argName,argSpec$args[[i]],envir=env);
argList[[i]] <- if (i%in%argSpec$copySpec) call('copy',as.symbol(argName)) else as.symbol(argName);
}; ## end for
callExpressions[[length(callExpressions)+1L]] <- do.call(call,c(list(testFuncName),argList),quote=T);
nms[length(nms)+1L] <- solType;
}; ## end for
names(callExpressions) <- nms;
callExpressions;
}; ## end setUpBenchmarkCall()
harmonize <- function(res) {
res <- as.data.frame(res); ## coerce to data.frame
for (ci in which(sapply(res,is.factor))) res[[ci]] <- as.character(res[[ci]]); ## coerce factor columns to character
for (ci in which(sapply(res,is.logical))) res[[ci]] <- as.integer(res[[ci]]); ## coerce logical columns to integer (works around sqldf quirk of munging logicals to integers)
##for (ci in which(sapply(res,inherits,'POSIXct'))) res[[ci]] <- as.double(res[[ci]]); ## coerce POSIXct columns to double (works around sqldf quirk of losing POSIXct class) ----- POSIXct doesn't work at all in sqldf.indexed
res <- res[order(names(res))]; ## order columns
res <- res[do.call(order,res),]; ## order rows
res;
}; ## end harmonize()
checkIdentical <- function(argSpecs,solTypes=getSolTypes()) {
for (joinType in getJoinTypes()) {
callExpressions <- setUpBenchmarkCall(argSpecs,joinType,solTypes);
if (length(callExpressions)<2L) next;
ex <- harmonize(eval(callExpressions[[1L]]));
for (i in seq(2L,len=length(callExpressions)-1L)) {
y <- harmonize(eval(callExpressions[[i]]));
if (!isTRUE(all.equal(ex,y,check.attributes=F))) {
ex <<- ex;
y <<- y;
solType <- names(callExpressions)[i];
stop(paste0('non-identical: ',solType,' ',joinType,'.'));
}; ## end if
}; ## end for
}; ## end for
invisible();
}; ## end checkIdentical()
testJoinType <- function(argSpecs,joinType,solTypes=getSolTypes(),metric=NULL,times=100L) {
callExpressions <- setUpBenchmarkCall(argSpecs,joinType,solTypes);
bm <- microbenchmark(list=callExpressions,times=times);
if (is.null(metric)) return(bm);
bm <- summary(bm);
res <- setNames(nm=names(callExpressions),bm[[metric]]);
attr(res,'unit') <- attr(bm,'unit');
res;
}; ## end testJoinType()
testAllJoinTypes <- function(argSpecs,solTypes=getSolTypes(),metric=NULL,times=100L) {
joinTypes <- getJoinTypes();
resList <- setNames(nm=joinTypes,lapply(joinTypes,function(joinType) testJoinType(argSpecs,joinType,solTypes,metric,times)));
if (is.null(metric)) return(resList);
units <- unname(unlist(lapply(resList,attr,'unit')));
res <- do.call(data.frame,c(list(join=joinTypes),setNames(nm=solTypes,rep(list(rep(NA_real_,length(joinTypes))),length(solTypes))),list(unit=units,stringsAsFactors=F)));
for (i in seq_along(resList)) res[i,match(names(resList[[i]]),names(res))] <- resList[[i]];
res;
}; ## end testAllJoinTypes()
testGrid <- function(makeArgSpecsFunc,sizes,overlaps,solTypes=getSolTypes(),joinTypes=getJoinTypes(),metric='median',times=100L) {
res <- expand.grid(size=sizes,overlap=overlaps,joinType=joinTypes,stringsAsFactors=F);
res[solTypes] <- NA_real_;
res$unit <- NA_character_;
for (ri in seq_len(nrow(res))) {
size <- res$size[ri];
overlap <- res$overlap[ri];
joinType <- res$joinType[ri];
argSpecs <- makeArgSpecsFunc(size,overlap);
checkIdentical(argSpecs,solTypes);
cur <- testJoinType(argSpecs,joinType,solTypes,metric,times);
res[ri,match(names(cur),names(res))] <- cur;
res$unit[ri] <- attr(cur,'unit');
}; ## end for
res;
}; ## end testGrid()
Here's a benchmark of the example based on the OP that I demonstrated earlier:
## OP's example, supplemented with a non-matching row in df2
argSpecs <- list(
default=list(copySpec=1:2,args=list(
df1 <- data.frame(CustomerId=1:6,Product=c(rep('Toaster',3L),rep('Radio',3L))),
df2 <- data.frame(CustomerId=c(2L,4L,6L,7L),State=c(rep('Alabama',2L),'Ohio','Texas')),
'CustomerId'
)),
data.table.unkeyed=list(copySpec=1:2,args=list(
as.data.table(df1),
as.data.table(df2),
'CustomerId'
)),
data.table.keyed=list(copySpec=1:2,args=list(
setkey(as.data.table(df1),CustomerId),
setkey(as.data.table(df2),CustomerId)
))
);
## prepare sqldf
initSqldf();
sqldf('create index df1_key on df1(CustomerId);'); ## upload and create an sqlite index on df1
sqldf('create index df2_key on df2(CustomerId);'); ## upload and create an sqlite index on df2
checkIdentical(argSpecs);
testAllJoinTypes(argSpecs,metric='median');
## join merge data.table.unkeyed data.table.keyed sqldf.unindexed sqldf.indexed plyr dplyr in.place unit
## 1 inner 644.259 861.9345 923.516 9157.752 1580.390 959.2250 270.9190 NA microseconds
## 2 left 713.539 888.0205 910.045 8820.334 1529.714 968.4195 270.9185 224.3045 microseconds
## 3 right 1221.804 909.1900 923.944 8930.668 1533.135 1063.7860 269.8495 218.1035 microseconds
## 4 full 1302.203 3107.5380 3184.729 NA NA 1593.6475 270.7055 NA microseconds
Here I benchmark on random input data, trying different scales and different patterns of key overlap between the two input tables. This benchmark is still restricted to the case of a single-column integer key. As well, to ensure that the in-place solution would work for both left and right joins of the same tables, all random test data uses 0..1:0..1
cardinality. This is implemented by sampling without replacement the key column of the first data.frame when generating the key column of the second data.frame.
makeArgSpecs.singleIntegerKey.optionalOneToOne <- function(size,overlap) {
com <- as.integer(size*overlap);
argSpecs <- list(
default=list(copySpec=1:2,args=list(
df1 <- data.frame(id=sample(size),y1=rnorm(size),y2=rnorm(size)),
df2 <- data.frame(id=sample(c(if (com>0L) sample(df1$id,com) else integer(),seq(size+1L,len=size-com))),y3=rnorm(size),y4=rnorm(size)),
'id'
)),
data.table.unkeyed=list(copySpec=1:2,args=list(
as.data.table(df1),
as.data.table(df2),
'id'
)),
data.table.keyed=list(copySpec=1:2,args=list(
setkey(as.data.table(df1),id),
setkey(as.data.table(df2),id)
))
);
## prepare sqldf
initSqldf();
sqldf('create index df1_key on df1(id);'); ## upload and create an sqlite index on df1
sqldf('create index df2_key on df2(id);'); ## upload and create an sqlite index on df2
argSpecs;
}; ## end makeArgSpecs.singleIntegerKey.optionalOneToOne()
## cross of various input sizes and key overlaps
sizes <- c(1e1L,1e3L,1e6L);
overlaps <- c(0.99,0.5,0.01);
system.time({ res <- testGrid(makeArgSpecs.singleIntegerKey.optionalOneToOne,sizes,overlaps); });
## user system elapsed
## 22024.65 12308.63 34493.19
I wrote some code to create log-log plots of the above results. I generated a separate plot for each overlap percentage. It's a little bit cluttered, but I like having all the solution types and join types represented in the same plot.
I used spline interpolation to show a smooth curve for each solution/join type combination, drawn with individual pch symbols. The join type is captured by the pch symbol, using a dot for inner, left and right angle brackets for left and right, and a diamond for full. The solution type is captured by the color as shown in the legend.
plotRes <- function(res,titleFunc,useFloor=F) {
solTypes <- setdiff(names(res),c('size','overlap','joinType','unit')); ## derive from res
normMult <- c(microseconds=1e-3,milliseconds=1); ## normalize to milliseconds
joinTypes <- getJoinTypes();
cols <- c(merge='purple',data.table.unkeyed='blue',data.table.keyed='#00DDDD',sqldf.unindexed='brown',sqldf.indexed='orange',plyr='red',dplyr='#00BB00',in.place='magenta');
pchs <- list(inner=20L,left='<',right='>',full=23L);
cexs <- c(inner=0.7,left=1,right=1,full=0.7);
NP <- 60L;
ord <- order(decreasing=T,colMeans(res[res$size==max(res$size),solTypes],na.rm=T));
ymajors <- data.frame(y=c(1,1e3),label=c('1ms','1s'),stringsAsFactors=F);
for (overlap in unique(res$overlap)) {
x1 <- res[res$overlap==overlap,];
x1[solTypes] <- x1[solTypes]*normMult[x1$unit]; x1$unit <- NULL;
xlim <- c(1e1,max(x1$size));
xticks <- 10^seq(log10(xlim[1L]),log10(xlim[2L]));
ylim <- c(1e-1,10^((if (useFloor) floor else ceiling)(log10(max(x1[solTypes],na.rm=T))))); ## use floor() to zoom in a little more, only sqldf.unindexed will break above, but xpd=NA will keep it visible
yticks <- 10^seq(log10(ylim[1L]),log10(ylim[2L]));
yticks.minor <- rep(yticks[-length(yticks)],each=9L)*1:9;
plot(NA,xlim=xlim,ylim=ylim,xaxs='i',yaxs='i',axes=F,xlab='size (rows)',ylab='time (ms)',log='xy');
abline(v=xticks,col='lightgrey');
abline(h=yticks.minor,col='lightgrey',lty=3L);
abline(h=yticks,col='lightgrey');
axis(1L,xticks,parse(text=sprintf('10^%d',as.integer(log10(xticks)))));
axis(2L,yticks,parse(text=sprintf('10^%d',as.integer(log10(yticks)))),las=1L);
axis(4L,ymajors$y,ymajors$label,las=1L,tick=F,cex.axis=0.7,hadj=0.5);
for (joinType in rev(joinTypes)) { ## reverse to draw full first, since it's larger and would be more obtrusive if drawn last
x2 <- x1[x1$joinType==joinType,];
for (solType in solTypes) {
if (any(!is.na(x2[[solType]]))) {
xy <- spline(x2$size,x2[[solType]],xout=10^(seq(log10(x2$size[1L]),log10(x2$size[nrow(x2)]),len=NP)));
points(xy$x,xy$y,pch=pchs[[joinType]],col=cols[solType],cex=cexs[joinType],xpd=NA);
}; ## end if
}; ## end for
}; ## end for
## custom legend
## due to logarithmic skew, must do all distance calcs in inches, and convert to user coords afterward
## the bottom-left corner of the legend will be defined in normalized figure coords, although we can convert to inches immediately
leg.cex <- 0.7;
leg.x.in <- grconvertX(0.275,'nfc','in');
leg.y.in <- grconvertY(0.6,'nfc','in');
leg.x.user <- grconvertX(leg.x.in,'in');
leg.y.user <- grconvertY(leg.y.in,'in');
leg.outpad.w.in <- 0.1;
leg.outpad.h.in <- 0.1;
leg.midpad.w.in <- 0.1;
leg.midpad.h.in <- 0.1;
leg.sol.w.in <- max(strwidth(solTypes,'in',leg.cex));
leg.sol.h.in <- max(strheight(solTypes,'in',leg.cex))*1.5; ## multiplication factor for greater line height
leg.join.w.in <- max(strheight(joinTypes,'in',leg.cex))*1.5; ## ditto
leg.join.h.in <- max(strwidth(joinTypes,'in',leg.cex));
leg.main.w.in <- leg.join.w.in*length(joinTypes);
leg.main.h.in <- leg.sol.h.in*length(solTypes);
leg.x2.user <- grconvertX(leg.x.in+leg.outpad.w.in*2+leg.main.w.in+leg.midpad.w.in+leg.sol.w.in,'in');
leg.y2.user <- grconvertY(leg.y.in+leg.outpad.h.in*2+leg.main.h.in+leg.midpad.h.in+leg.join.h.in,'in');
leg.cols.x.user <- grconvertX(leg.x.in+leg.outpad.w.in+leg.join.w.in*(0.5+seq(0L,length(joinTypes)-1L)),'in');
leg.lines.y.user <- grconvertY(leg.y.in+leg.outpad.h.in+leg.main.h.in-leg.sol.h.in*(0.5+seq(0L,length(solTypes)-1L)),'in');
leg.sol.x.user <- grconvertX(leg.x.in+leg.outpad.w.in+leg.main.w.in+leg.midpad.w.in,'in');
leg.join.y.user <- grconvertY(leg.y.in+leg.outpad.h.in+leg.main.h.in+leg.midpad.h.in,'in');
rect(leg.x.user,leg.y.user,leg.x2.user,leg.y2.user,col='white');
text(leg.sol.x.user,leg.lines.y.user,solTypes[ord],cex=leg.cex,pos=4L,offset=0);
text(leg.cols.x.user,leg.join.y.user,joinTypes,cex=leg.cex,pos=4L,offset=0,srt=90); ## srt rotation applies *after* pos/offset positioning
for (i in seq_along(joinTypes)) {
joinType <- joinTypes[i];
points(rep(leg.cols.x.user[i],length(solTypes)),ifelse(colSums(!is.na(x1[x1$joinType==joinType,solTypes[ord]]))==0L,NA,leg.lines.y.user),pch=pchs[[joinType]],col=cols[solTypes[ord]]);
}; ## end for
title(titleFunc(overlap));
readline(sprintf('overlap %.02f',overlap));
}; ## end for
}; ## end plotRes()
titleFunc <- function(overlap) sprintf('R merge solutions: single-column integer key, 0..1:0..1 cardinality, %d%% overlap',as.integer(overlap*100));
plotRes(res,titleFunc,T);
Here's a second large-scale benchmark that's more heavy-duty, with respect to the number and types of key columns, as well as cardinality. For this benchmark I use three key columns: one character, one integer, and one logical, with no restrictions on cardinality (that is, 0..*:0..*
). (In general it's not advisable to define key columns with double or complex values due to floating-point comparison complications, and basically no one ever uses the raw type, much less for key columns, so I haven't included those types in the key columns. Also, for information's sake, I initially tried to use four key columns by including a POSIXct key column, but the POSIXct type didn't play well with the sqldf.indexed
solution for some reason, possibly due to floating-point comparison anomalies, so I removed it.)
makeArgSpecs.assortedKey.optionalManyToMany <- function(size,overlap,uniquePct=75) {
## number of unique keys in df1
u1Size <- as.integer(size*uniquePct/100);
## (roughly) divide u1Size into bases, so we can use expand.grid() to produce the required number of unique key values with repetitions within individual key columns
## use ceiling() to ensure we cover u1Size; will truncate afterward
u1SizePerKeyColumn <- as.integer(ceiling(u1Size^(1/3)));
## generate the unique key values for df1
keys1 <- expand.grid(stringsAsFactors=F,
idCharacter=replicate(u1SizePerKeyColumn,paste(collapse='',sample(letters,sample(4:12,1L),T))),
idInteger=sample(u1SizePerKeyColumn),
idLogical=sample(c(F,T),u1SizePerKeyColumn,T)
##idPOSIXct=as.POSIXct('2016-01-01 00:00:00','UTC')+sample(u1SizePerKeyColumn)
)[seq_len(u1Size),];
## rbind some repetitions of the unique keys; this will prepare one side of the many-to-many relationship
## also scramble the order afterward
keys1 <- rbind(keys1,keys1[sample(nrow(keys1),size-u1Size,T),])[sample(size),];
## common and unilateral key counts
com <- as.integer(size*overlap);
uni <- size-com;
## generate some unilateral keys for df2 by synthesizing outside of the idInteger range of df1
keys2 <- data.frame(stringsAsFactors=F,
idCharacter=replicate(uni,paste(collapse='',sample(letters,sample(4:12,1L),T))),
idInteger=u1SizePerKeyColumn+sample(uni),
idLogical=sample(c(F,T),uni,T)
##idPOSIXct=as.POSIXct('2016-01-01 00:00:00','UTC')+u1SizePerKeyColumn+sample(uni)
);
## rbind random keys from df1; this will complete the many-to-many relationship
## also scramble the order afterward
keys2 <- rbind(keys2,keys1[sample(nrow(keys1),com,T),])[sample(size),];
##keyNames <- c('idCharacter','idInteger','idLogical','idPOSIXct');
keyNames <- c('idCharacter','idInteger','idLogical');
## note: was going to use raw and complex type for two of the non-key columns, but data.table doesn't seem to fully support them
argSpecs <- list(
default=list(copySpec=1:2,args=list(
df1 <- cbind(stringsAsFactors=F,keys1,y1=sample(c(F,T),size,T),y2=sample(size),y3=rnorm(size),y4=replicate(size,paste(collapse='',sample(letters,sample(4:12,1L),T)))),
df2 <- cbind(stringsAsFactors=F,keys2,y5=sample(c(F,T),size,T),y6=sample(size),y7=rnorm(size),y8=replicate(size,paste(collapse='',sample(letters,sample(4:12,1L),T)))),
keyNames
)),
data.table.unkeyed=list(copySpec=1:2,args=list(
as.data.table(df1),
as.data.table(df2),
keyNames
)),
data.table.keyed=list(copySpec=1:2,args=list(
setkeyv(as.data.table(df1),keyNames),
setkeyv(as.data.table(df2),keyNames)
))
);
## prepare sqldf
initSqldf();
sqldf(paste0('create index df1_key on df1(',paste(collapse=',',keyNames),');')); ## upload and create an sqlite index on df1
sqldf(paste0('create index df2_key on df2(',paste(collapse=',',keyNames),');')); ## upload and create an sqlite index on df2
argSpecs;
}; ## end makeArgSpecs.assortedKey.optionalManyToMany()
sizes <- c(1e1L,1e3L,1e5L); ## 1e5L instead of 1e6L to respect more heavy-duty inputs
overlaps <- c(0.99,0.5,0.01);
solTypes <- setdiff(getSolTypes(),'in.place');
system.time({ res <- testGrid(makeArgSpecs.assortedKey.optionalManyToMany,sizes,overlaps,solTypes); });
## user system elapsed
## 38895.50 784.19 39745.53
The resulting plots, using the same plotting code given above:
titleFunc <- function(overlap) sprintf('R merge solutions: character/integer/logical key, 0..*:0..* cardinality, %d%% overlap',as.integer(overlap*100));
plotRes(res,titleFunc,F);
It seems that there is in fact a pure CSS solution, requiring only the css attr
expression, generated content and attribute selectors (which suggests that it works as far back as IE8):
https://jsfiddle.net/z42r2vv0/2/
a {
position: relative;
display: inline-block;
margin-top: 20px;
}
a[title]:hover::after {
content: attr(title);
position: absolute;
top: -100%;
left: 0;
}
_x000D_
<a href="http://www.google.com/" title="Hello world!">
Hover over me
</a>
_x000D_
update w/ input from @ViROscar: please note that it's not necessary to use any specific attribute, although I've used the "title" attribute in the example above; actually my recommendation would be to use the "alt" attribute, as there is some chance that the content will be accessible to users unable to benefit from CSS.
update again I'm not changing the code because the "title" attribute has basically come to mean the "tooltip" attribute, and it's probably not a good idea to hide important text inside a field only accessible on hover, but if you're interested in making this text accessible the "aria-label" attribute seems like the best place for it: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute
Refer: http://www.wellho.net/mouth/754_tar-jar-war-ear-sar-files.html
tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge
Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure
war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes
ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files
I have put something like this in my Controller class and it worked:
IdentityUser user = await userManager.FindByNameAsync(HttpContext.User.Identity.Name);
where userManager is an instance of Microsoft.AspNetCore.Identity.UserManager class (with all weird setup that goes with it).
A DTU is a unit of measure for the performance of a service tier and is a summary of several database characteristics. Each service tier has a certain number of DTUs assigned to it as an easy way to compare the performance level of one tier versus another.
Database Throughput Unit (DTU): DTUs provide a way to describe the relative capacity of a performance level of Basic, Standard, and Premium databases. DTUs are based on a blended measure of CPU, memory, reads, and writes. As DTUs increase, the power offered by the performance level increases. For example, a performance level with 5 DTUs has five times more power than a performance level with 1 DTU. A maximum DTU quota applies to each server.
The DTU Quota applies to the server, not the individual databases and each server has a maximum of 1600 DTUs. The DTU% is the percentage of units your particular database is using and it seems that this number can go over 100% of the DTU rating of the service tier (I assume to the limit of the server). This percentage number is designed to help you choose the appropriate service tier.
From down toward the bottom of this announcement:
For example, if your DTU consumption shows a value of 80%, it indicates it is consuming DTU at the rate of 80% of the limit an S2 database would have. If you see values greater than 100% in this view it means that you need a performance tier larger than S2.
As an example, let’s say you see a percentage value of 300%. This tells you that you are using three times more resources than would be available in an S2. To determine a reasonable starting size, compare the DTUs available in an S2 (50 DTUs) with the next higher sizes (P1 = 100 DTUs, or 200% of S2, P2 = 200 DTUs or 400% of S2). Because you are at 300% of S2 you would want to start with a P2 and re-test.
Here is a sample script and test case. Covers positioned elements, visibilty: hidden, display: none. Didn't test z-index, assume it works.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<style type="text/css">
div {
width: 200px;
border: 1px solid red;
}
p {
border: 2px solid green;
}
.r {
border: 1px solid #BB3333;
background: #EE9999;
position: relative;
top: -50px;
height: 2em;
}
.of {
overflow: hidden;
height: 2em;
word-wrap: none;
}
.of p {
width: 100%;
}
.of pre {
display: inline;
}
.iv {
visibility: hidden;
}
.dn {
display: none;
}
</style>
<script src="http://www.prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js"></script>
<script>
function isVisible(elem){
if (Element.getStyle(elem, 'visibility') == 'hidden' || Element.getStyle(elem, 'display') == 'none') {
return false;
}
var topx, topy, botx, boty;
var offset = Element.positionedOffset(elem);
topx = offset.left;
topy = offset.top;
botx = Element.getWidth(elem) + topx;
boty = Element.getHeight(elem) + topy;
var v = false;
for (var x = topx; x <= botx; x++) {
for(var y = topy; y <= boty; y++) {
if (document.elementFromPoint(x,y) == elem) {
// item is visible
v = true;
break;
}
}
if (v == true) {
break;
}
}
return v;
}
window.onload=function() {
var es = Element.descendants('body');
for (var i = 0; i < es.length; i++ ) {
if (!isVisible(es[i])) {
alert(es[i].tagName);
}
}
}
</script>
</head>
<body id='body'>
<div class="s"><p>This is text</p><p>More text</p></div>
<div class="r">This is relative</div>
<div class="of"><p>This is too wide...</p><pre>hidden</pre>
<div class="iv">This is invisible</div>
<div class="dn">This is display none</div>
</body>
</html>
As a new set of tests to show @EriF89 is still right after all these years:
$ python -m timeit -s "l={k:k for k in xrange(5000)}" "[i for i in xrange(10000) if i in l]"
1000 loops, best of 3: 1.84 msec per loop
$ python -m timeit -s "l=[k for k in xrange(5000)]" "[i for i in xrange(10000) if i in l]"
10 loops, best of 3: 573 msec per loop
$ python -m timeit -s "l=tuple([k for k in xrange(5000)])" "[i for i in xrange(10000) if i in l]"
10 loops, best of 3: 587 msec per loop
$ python -m timeit -s "l=set([k for k in xrange(5000)])" "[i for i in xrange(10000) if i in l]"
1000 loops, best of 3: 1.88 msec per loop
Here we also compare a tuple
, which are known to be faster than lists
(and use less memory) in some use cases. In the case of lookup table, the tuple
faired no better .
Both the dict
and set
performed very well. This brings up an interesting point tying into @SilentGhost answer about uniqueness: if the OP has 10M values in a data set, and it's unknown if there are duplicates in them, then it would be worth keeping a set/dict of its elements in parallel with the actual data set, and testing for existence in that set/dict. It's possible the 10M data points only have 10 unique values, which is a much smaller space to search!
SilentGhost's mistake about dicts is actually illuminating because one could use a dict to correlate duplicated data (in values) into a nonduplicated set (keys), and thus keep one data object to hold all data, yet still be fast as a lookup table. For example, a dict key could be the value being looked up, and the value could be a list of indices in an imaginary list where that value occurred.
For example, if the source data list to be searched was l=[1,2,3,1,2,1,4]
, it could be optimized for both searching and memory by replacing it with this dict:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> l=[1,2,3,1,2,1,4]
>>> for i, e in enumerate(l):
... d[e].append(i)
>>> d
defaultdict(<class 'list'>, {1: [0, 3, 5], 2: [1, 4], 3: [2], 4: [6]})
With this dict, one can know:
2 in d
returns True
)d[2]
returns list of indices where data was found in original data list: [1, 4]
)You need to use table-layout:fixed
in order for CSS ellipsis to work on the table cells.
.table {
table-layout:fixed;
}
.table td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
you can get the nodejs configuration from http://nodejs.org/
The important thing you need to keep in your mind is about its configuration in file app.js which consists of port number host and other settings these are settings working for me
backendSettings = { "scheme":"https / http ", "host":"Your website url", "port":49165, //port number 'sslKeyPath': 'Path for key', 'sslCertPath': 'path for SSL certificate', 'sslCAPath': '', "resource":"/socket.io", "baseAuthPath": '/nodejs/', "publishUrl":"publish", "serviceKey":"", "backend":{ "port":443, "scheme": 'https / http', //whatever is your website scheme "host":"host name", "messagePath":"/nodejs/message/"}, "clientsCanWriteToChannels":false, "clientsCanWriteToClients":false, "extensions":"", "debug":false, "addUserToChannelUrl": 'user/channel/add/:channel/:uid', "publishMessageToContentChannelUrl": 'content/token/message', "transports":["websocket", "flashsocket", "htmlfile", "xhr-polling", "jsonp-polling"], "jsMinification":true, "jsEtag":true, "logLevel":1};
In this if you are getting "Error: listen EADDRINUSE" then please change the port number i.e, here I am using "49165" so you can use other port such as 49170 or some other port.
For this you can refer to the following article
http://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-shared-hosting-accounts
Had to look it up in the specs:
Class's getResource() - documentation states the difference:
This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.
Steps to remove index.php from url for your wordpress website.
<?php
phpinfo?();
?>
Now run this file - www.yoursite.com/phpinfo.php and it will show mod_rewrite at Load modules section. If not enabled then perform below commands at your terminal.
sudo a2enmod rewrite
sudo service apache2 restart
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Further make permission of .htaccess to 666 so that it become writable and now you can do changes in your wordpress permalinks.
Now go to Settings -> permalinks -> and change to your needed url format. Remove this code /index.php/%year%/%monthnum%/%day%/%postname%/ and insert this code on Custom Structure: /%postname%/
If still not succeeded then check your hosting, mine was digitalocean server, so I cleared it myself
Edited the file /etc/apache2/sites-enabled/000-default.conf
Added this line after DocumentRoot /var/www/html
<Directory /var/www/html>
AllowOverride All
</Directory>
Restart your apache server
Note: /var/www/html will be your document root
Ok, I solved it by adding the url for the background image at the end of the line.
Here's my working code:
.css {_x000D_
background: -moz-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0)), color-stop(59%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0.65))), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -o-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -ms-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
height: 200px;_x000D_
_x000D_
}
_x000D_
<div class="css"></div>
_x000D_
Assuming you're happy with truncating towards zero, just cast:
double d = 1234.56;
long x = (long) d; // x = 1234
This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.
if you want to change menu item icons, arrow icon (back/up), and 3 dots icon you can use android:tint
<style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:tint">@color/your_color</item>
</style>
I solved this problem for myself using grunt. I have the grunt script below. What the script does is takes the command line parameter of the specific test to run and creates a copy of test.ts and puts this specific test name in there.
To run this, first install grunt-cli using:
npm install -g grunt-cli
Put the below grunt dependencies in your package.json:
"grunt": "^1.0.1",
"grunt-contrib-clean": "^1.0.0",
"grunt-contrib-copy": "^1.0.0",
"grunt-exec": "^2.0.0",
"grunt-string-replace": "^1.3.1"
To run it save the below grunt file as Gruntfile.js in your root folder. Then from command line run it as:
grunt --target=app.component
This will run app.component.spec.ts.
Grunt file is as below:
/*
This gruntfile is used to run a specific test in watch mode. Example: To run app.component.spec.ts , the Command is:
grunt --target=app.component
Do not specific .spec.ts. If no target is specified it will run all tests.
*/
module.exports = function(grunt) {
var target = grunt.option('target') || '';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: ['temp.conf.js','src/temp-test.ts'],
copy: {
main: {
files: [
{expand: false, cwd: '.', src: ['karma.conf.js'], dest: 'temp.conf.js'},
{expand: false, cwd: '.', src: ['src/test.ts'], dest: 'src/temp-test.ts'}
],
}
},
'string-replace': {
dist: {
files: {
'temp.conf.js': 'temp.conf.js',
'src/temp-test.ts': 'src/temp-test.ts'
},
options: {
replacements: [{
pattern: /test.ts/ig,
replacement: 'temp-test.ts'
},
{
pattern: /const context =.*/ig,
replacement: 'const context = require.context(\'./\', true, /'+target+'\\\.spec\\\.ts$/);'
}]
}
}
},
'exec': {
sleep: {
//The sleep command is needed here, else webpack compile fails since it seems like the files in the previous step were touched too recently
command: 'ping 127.0.0.1 -n 4 > nul',
stdout: true,
stderr: true
},
ng_test: {
command: 'ng test --config=temp.conf.js',
stdout: true,
stderr: true
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-string-replace');
grunt.loadNpmTasks('grunt-exec');
// Default task(s).
grunt.registerTask('default', ['clean','copy','string-replace','exec']);
};
This is a very fast solution for one-dimensional atomic vectors. It relies on match()
, so it is compatible with NA
:
x <- c("a", NA, "a", "c", "a", "b", NA, "c")
fn <- function(x) {
u <- unique.default(x)
out <- list(x = u, freq = .Internal(tabulate(match(x, u), length(u))))
class(out) <- "data.frame"
attr(out, "row.names") <- seq_along(u)
out
}
fn(x)
#> x freq
#> 1 a 3
#> 2 <NA> 2
#> 3 c 2
#> 4 b 1
You could also tweak the algorithm so that it doesn't run unique()
.
fn2 <- function(x) {
y <- match(x, x)
out <- list(x = x, freq = .Internal(tabulate(y, length(x)))[y])
class(out) <- "data.frame"
attr(out, "row.names") <- seq_along(x)
out
}
fn2(x)
#> x freq
#> 1 a 3
#> 2 <NA> 2
#> 3 a 3
#> 4 c 2
#> 5 a 3
#> 6 b 1
#> 7 <NA> 2
#> 8 c 2
In cases where that output is desirable, you probably don't even need it to re-return the original vector, and the second column is probably all you need. You can get that in one line with the pipe:
match(x, x) %>% `[`(tabulate(.), .)
#> [1] 3 2 3 2 3 1 2 2
I realized a Open Source library on GitHub CircularProgressBar that does exactly what you want the simplest way possible:
To make a circular ProgressBar add CircularProgressBar in your layout XML and add CircularProgressBar library in your projector or you can also grab it via Gradle:
compile 'com.mikhaellopez:circularprogressbar:1.0.0'
<com.mikhaellopez.circularprogressbar.CircularProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:background_progressbar_color="#FFCDD2"
app:background_progressbar_width="5dp"
app:progressbar_color="#F44336"
app:progressbar_width="10dp" />
You must use the following properties in your XML to change your CircularProgressBar.
Properties:
app:progress
(integer) >> default 0app:progressbar_color
(color) >> default BLACKapp:background_progressbar_color
(color) >> default GRAYapp:progressbar_width
(dimension) >> default 7dpapp:background_progressbar_width
(dimension) >> default 3dpCircularProgressBar circularProgressBar = (CircularProgressBar)findViewById(R.id.yourCircularProgressbar);
circularProgressBar.setColor(ContextCompat.getColor(this, R.color.progressBarColor));
circularProgressBar.setBackgroundColor(ContextCompat.getColor(this, R.color.backgroundProgressBarColor));
circularProgressBar.setProgressBarWidth(getResources().getDimension(R.dimen.progressBarWidth));
circularProgressBar.setBackgroundProgressBarWidth(getResources().getDimension(R.dimen.backgroundProgressBarWidth));
int animationDuration = 2500; // 2500ms = 2,5s
circularProgressBar.setProgressWithAnimation(65, animationDuration); // Default duration = 1500ms
Fork or Download this library here >> https://github.com/lopspower/CircularProgressBar
I just had this problem and I first switched to another directory and then switched back and the problem was fixed.
Easiest way is use this way
my_var=`echo 2`
echo $my_var
output
: 2
note that is not simple single quote is back quote ( ` ).
You can set an ENV if you want your Time.now
and DateTime.now
to respond in UTC time.
require 'date'
Time.now #=> 2015-11-30 11:37:14 -0800
DateTime.now.to_s #=> "2015-11-30T11:37:25-08:00"
ENV['TZ'] = 'UTC'
Time.now #=> 2015-11-30 19:37:38 +0000
DateTime.now.to_s #=> "2015-11-30T19:37:36+00:00"
If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw
always interrupt the execution flow of the current method. a try
/catch
block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.
Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/
Very simple methods Just go to the terminal and the type following
rails g devise:controllers users //This will create devise controllers in controllers/users folder
Next to use custom views
rails g devise:views users //This will create devise views in views/users folder
now in your route.rb file
devise_for :users, controllers: {
:sessions => "users/sessions",
:registrations => "users/registrations" }
You can add other controllers too. This will make devise to use controllers in users folder and views in users folder.
Now you can customize your views as your desire and add your logic to controllers in controllers/users folder. Enjoy !
i use this
<style>
html, body{height:100%;margin:0;padding:0 0}
.container-fluid{height:100%;display:table;width:100%;padding-right:0;padding-left: 0}
.row-fluid{height:100%;display:table-cell;vertical-align:middle;width:100%}
.centering{float:none;margin:0 auto}
</style>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="offset3 span6 centering">
content here
</div>
</div>
</div>
</body>
The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.
Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.
import React, {Component} from 'react';
export default class ChatOutPut extends Component {
constructor(props) {
super(props);
this.state = {
messages: props.chatmessages
};
}
componentDidUpdate = (previousProps, previousState) => {
if (this.refs.chatoutput != null) {
this.refs.chatoutput.scrollTop = this.refs.chatoutput.scrollHeight;
}
}
renderMessage(data) {
return (
<div key={data.key}>
{data.message}
</div>
);
}
render() {
return (
<div ref='chatoutput' className={classes.chatoutputcontainer}>
{this.state.messages.map(this.renderMessage, this)}
</div>
);
}
}
function intersectionOfArrays(arr1, arr2) {
return arr1.filter((element) => arr2.indexOf(element) !== -1).filter((element, pos, self) => self.indexOf(element) == pos);
}
Even though this answer was too late, I'm adding it because I also went through a horrible time finding answer for the same matter. Only different was, I was struggling with AWS Comprehend Medical API.
At the moment I'm writing this answer, if anyone come across the same issue with any AWS SDKs please downgrade jackson-annotaions or any jackson dependencies to 2.8.* versions. The latest 2.9.* versions does not working properly with AWS SDK for some reason. Anyone have any idea about the reason behind that feel free to comment below.
Just in case if anyone is lazy to google maven repos, I have linked down necessary repos.Check them out!
Basically, what is happening is that your user is either closing the browser tab, or is navigating away to a different page, before communication was complete. Your webserver (Jetty) generates this exception because it is unable to send the remaining bytes.
org.eclipse.jetty.io.EofException: null
! at org.eclipse.jetty.http.HttpGenerator.flushBuffer(HttpGenerator.java:914)
! at org.eclipse.jetty.http.HttpGenerator.complete(HttpGenerator.java:798)
! at org.eclipse.jetty.server.AbstractHttpConnection.completeResponse(AbstractHttpConnection.java:642)
!
This is not an error on your application logic side. This is simply due to user behavior. There is nothing wrong in your code per se.
There are two things you may be able to do:
for some reason sharex was set to True so I turned it back to False and it worked fine.
df.plot(........,sharex=False)
I stumbled upon an interesting reason for a gigantic .xlsx file. Original workbook had 20 sheets or so, was 20 MB I made a new workbook with 1 of the sheets, so it would be more manageable: still 11.5 MB Imagine my surprise to find that the single sheet in the new workbook had 1,041,776 (count 'em!) blank rows. Now it's 13.5 KB
I made an extension method based on this MSDN article. This is how you can determine whether a socket is still connected.
public static bool IsConnected(this Socket client)
{
bool blockingState = client.Blocking;
try
{
byte[] tmp = new byte[1];
client.Blocking = false;
client.Send(tmp, 0, 0);
return true;
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
return true;
}
else
{
return false;
}
}
finally
{
client.Blocking = blockingState;
}
}
CSS3 Simple Way
height: calc(100% - 10px); // 10px is height of your first div...
all major browsers these days support it, so go ahead if you don't have requirement to support vintage browsers.
define({
"data": "XYZ"
});
var fs = require("fs");
var vm = require("vm");
function include(path, context) {
var code = fs.readFileSync(path, 'utf-8');
vm.runInContext(code, vm.createContext(context));
}
// Include file
var customContext = {
"define": function (data) {
console.log(data);
}
};
include('./fileToInclude.js', customContext);
This worked for me:
foreach (var item in FirmNameList){
if (FirmNames != "")
{
FirmNames += ",\r\n"
}
FirmNames += item;
}
When Laravel tries to connect to database, if the connection fails or if it finds any errors it will return a PDOException
error. We can catch this error and redirect the action
Add the following code in the app/filtes.php
file.
App::error(function(PDOException $exception)
{
Log::error("Error connecting to database: ".$exception->getMessage());
return "Error connecting to database";
});
Hope this is helpful.
If it's just a true/false test, have your function return 0
for success, and return 1
for failure. The test would then be:
if function_name; then
do something
else
error condition
fi
Both the two most upvoted answers are wrong. It should have nothing to do with "store different/multiple languages". You can support Spanish characters like ñ
and English, with just common varchar
field and Latin1_General_CI_AS
COLLATION
, e.g.
Short Version
You should use NVARCHAR
/NCHAR
whenever the ENCODING
, which is determined by COLLATION
of the field, doesn't support the characters needed.
Also, depending on the SQL Server version, you can use specific COLLATIONs
, like Latin1_General_100_CI_AS_SC_UTF8
which is available since SQL Server 2019. Setting this collation on a VARCHAR
field (or entire table/database), will use UTF-8
ENCODING
for storing and handling the data on that field, allowing fully support UNICODE
characters, and hence any languages embraced by it.
To FULLY UNDERSTAND:
To fully understand what I'm about to explain, it's mandatory to have the concepts of UNICODE
, ENCODING
and COLLATION
all extremely clear in your head. If you don't, then first take a look below at my humble and simplified explanation on "What is UNICODE, ENCODING, COLLATION and UTF-8, and how they are related" section and supplied documentation links. Also, everything I say here is specific to Microsoft SQL Server
, and how it stores and handles data in char
/nchar
and varchar
/nvarchar
fields.
Let's say we wanna store a peculiar text on our MSSQL Server database. It could be an Instagram comment as "I love stackoverflow! ".
The plain English part would be perfectly supported even by ASCII, but since there are also an emoji, which is a character specified in the UNICODE
standard, we need an ENCODING
that supports this Unicode character.
MSSQL Server uses the COLLATION
to determine what ENCODING
is used on char
/nchar
/varchar
/nvarchar
fields. So, differently than a lot think, COLLATION
is not only about sorting and comparing data, but also about ENCODING
, and by consequence: how our data will be stored!
So, HOW WE KNOW WHAT IS THE ENCODING USED BY OUR COLLATION? With this:
SELECT COLLATIONPROPERTY( 'Latin1_General_CI_AI' , 'CodePage' ) AS [CodePage]
--returns 1252
This simple SQL returns the Windows Code Page
for a COLLATION
. A Windows Code Page
is nothing more than another mapping to ENCODINGs
. For the Latin1_General_CI_AI
COLLATION
it returns the Windows Code Page
code 1252
, that maps to Windows-1252
ENCODING
.
So, for a varchar
column, with Latin1_General_CI_AI
COLLATION
, this field will handle its data using the Windows-1252
ENCODING
, and only correctly store characters supported by this encoding.
If we check the Windows-1252 ENCODING
specification Character List for Windows-1252, we will find out that this encoding won't support our emoji character. And if we still try it out:
OK, SO HOW CAN WE SOLVE THIS?? Actually, it depends, and that is GOOD!
NCHAR
/NVARCHAR
Before SQL Server 2019 all we had was NCHAR
and NVARCHAR
fields. Some say they are UNICODE
fields. THAT IS WRONG!. Again, it depends on the field's COLLATION
and also SQLServer Version.
Microsoft's "nchar and nvarchar (Transact-SQL)" documentation specifies perfectly:
Starting with SQL Server 2012 (11.x), when a Supplementary Character (SC) enabled collation is used, these data types store the full range of Unicode character data and use the UTF-16 character encoding. If a non-SC collation is specified, then these data types store only the subset of character data supported by the UCS-2 character encoding.
In other words, if we use SQL Server older that 2012, like SQL Server 2008 R2 for example, the ENCODING
for those fields will use UCS-2 ENCODING
which support a subset of UNICODE
. But if we use SQL Server 2012 or newer, and define a COLLATION
that has Supplementary Character
enabled, than with our field will use the UTF-16
ENCODING
, that fully supports UNICODE
.
BUT WHAIT, THERE IS MORE! WE CAN USE UTF-8 NOW!!
CHAR
/VARCHAR
Starting with SQL Server 2019, WE CAN USE CHAR
/VARCHAR
fields and still fully support UNICODE
using UTF-8
ENCODING
!!!
From Microsoft's "char and varchar (Transact-SQL)" documentation:
Starting with SQL Server 2019 (15.x), when a UTF-8 enabled collation is used, these data types store the full range of Unicode character data and use the UTF-8 character encoding. If a non-UTF-8 collation is specified, then these data types store only a subset of characters supported by the corresponding code page of that collation.
Again, in other words, if we use SQL Server older that 2019, like SQL Server 2008 R2 for example, we need to check the ENCODING
using the method explained before. But if we use SQL Server 2019 or newer, and define a COLLATION
like Latin1_General_100_CI_AS_SC_UTF8
, then our field will use UTF-8
ENCODING
which is by far the most used and efficient encoding that supports all the UNICODE
characters.
Bonus Information:
Regarding the OP's observation on "I have seen that most of the European languages (German, Italian, English, ...) are fine in the same database in VARCHAR columns", I think it's nice to know why it is:
For the most common COLLATIONs
, like the default ones as Latin1_General_CI_AI
or SQL_Latin1_General_CP1_CI_AS
the ENCODING
will be Windows-1252
for varchar
fields. If we take a look on it's documentation, we can see that it supports:
English, Irish, Italian, Norwegian, Portuguese, Spanish, Swedish. Plus also German, Finnish and French. And Dutch except the ? character
But as I said before, it's not about language, it's about what characters do you expect to support/store, as shown in the emoji example, or some sentence like "The electric resistance of a lithium battery is 0.5O" where we have again plain English, and a Greek letter/character "omega" (which is the symbol for resistance in ohms), which won't be correctly handled by Windows-1252
ENCODING
.
Conclusion:
So, there it is! When use char
/nchar
and varchar
/nvarchar
depends on the characters that you want to support, and also the version of your SQL Server that will determines which COLLATIONs
and hence the ENCODINGs
you have available.
What is UNICODE, ENCODING, COLLATION and UTF-8, and how they are related
Note: all the explanations below are simplifications. Please, refer to the supplied documentation links to know all the details about those concepts.
UNICODE
- Is a standard, a convention, that aims to regulate all the characters in a unified and organized table. In this table, every character has an unique number. This number is commonly called character's code point
.
UNICODE IS NOT AN ENCODING!
ENCODING
- Is a mapping between a character and a byte/bytes sequence. So a encoding is used to "transform" a character to bytes and also the other way around, from bytes to a character. Among the most popular ones are UTF-8
, ISO-8859-1
, Windows-1252
and ASCII
. You can think of it as a "conversion table" (i really simplified here).
COLLATION
- That one is important. Even Microsoft's documentation doesn't let this clear as it should be. A Collation specifies how your data would be sorted, compared, AND STORED!. Yeah, I bet you was not expecting for that last one, right!? The collations on SQL Server
determines too what would be the ENCODING
used on that particular char
/nchar
/varchar
/nvarchar
field.
ASCII ENCODING
- Was one of the firsts encodings. It is both the character table (like an own tiny version of UNICODE
) and its byte mappings. So it doesn't map a byte to UNICODE
, but map a byte to its own character's table. Also, it always use only 7bits, and supported 128 different characters. It was enough to support all English letters upper and down cased, numbers, punctuation and some other limited number of characters. The problem with ASCII is that since it only used 7bits and almost every computer was 8bits at the time, there were another 128 possibilities of characters to be "explored", and everybody started to map this "available" bytes to its own table of characters, creating a lot of different ENCODINGs
.
UTF-8 ENCODING
- This is another ENCODING
, one of the most (if not the most) used ENCODING
around. It uses variable byte width (one character can be from 1 to 6 bytes long, by specification) and fully supports all UNICODE
characters.
Windows-1252 ENCODING
- Also one of the most used ENCODING
, it's widely used on SQL Server. It's fixed-size, so every one character is always 1byte. It also supports a lot of accents, from various languages but doesn't support all existing, nor supports UNICODE
. That's why your varchar
field with a common collation like Latin1_General_CI_AS
supports á
,é
,ñ
characters, even that it isn't using a supportive UNICODE
ENCODING
.
Resources:
https://blog.greglow.com/2019/07/25/sql-think-that-varchar-characters-if-so-think-again/
https://medium.com/@apiltamang/unicode-utf-8-and-ascii-encodings-made-easy-5bfbe3a1c45a
https://www.johndcook.com/blog/2019/09/09/how-utf-8-works/
https://www.w3.org/International/questions/qa-what-is-encoding
https://en.wikipedia.org/wiki/List_of_Unicode_characters
https://www.fileformat.info/info/charset/windows-1252/list.htm
https://docs.microsoft.com/en-us/sql/t-sql/data-types/char-and-varchar-transact-sql?view=sql-server-ver15
https://docs.microsoft.com/en-us/sql/t-sql/data-types/nchar-and-nvarchar-transact-sql?view=sql-server-ver15
https://docs.microsoft.com/en-us/sql/t-sql/statements/windows-collation-name-transact-sql?view=sql-server-ver15
https://docs.microsoft.com/en-us/sql/t-sql/statements/sql-server-collation-name-transact-sql?view=sql-server-ver15
https://docs.microsoft.com/en-us/sql/relational-databases/collations/collation-and-unicode-support?view=sql-server-ver15#SQL-collations
SQL Server default character encoding
https://en.wikipedia.org/wiki/Windows_code_page
I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.
On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.
I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.
So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.
To push the contents of foo to origin/master, you first need to set its upstream:
git checkout foo
git branch -u origin/master
Then you can push to this branch using:
git push origin HEAD:master
In the last command you can add --force to replace the entire history of origin/master with that of foo.
Noone here said anything about the one that comes with C++0x. If you are using a compiler and the STL that supports C++0x you could just use that instead of having another lib in your project.
body.bg {
background-size: cover;
background-repeat: no-repeat;
min-height: 100vh;
background: white url(../images/bg-404.jpg) center center no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
}
Try This
_x000D_
_x000D_
body.bg {_x000D_
background-size: cover;_x000D_
background-repeat: no-repeat;_x000D_
min-height: 100vh;_x000D_
background: white url(http://lorempixel.com/output/city-q-c-1920-1080-7.jpg) center center no-repeat;_x000D_
-webkit-background-size: cover;_x000D_
-moz-background-size: cover;_x000D_
-o-background-size: cover;_x000D_
}
_x000D_
<body class="bg">_x000D_
_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_
In addition, you need the "AllowOverride Options" directive for this to work. (Apache 2.2.15)
Adding this answer because the previous answers permanently delete your changes
git stash -u
Explanation: Stash local changes including untracked changes (-u
flag). The command saves your local modifications away and reverts the working directory to match the HEAD commit.
git stash pop
Explanation: The command will reapply the changes to the top of the current working tree state.
git stash drop
Explanation: The command will permanently remove the stashed entry
I faced this same problem. Go to the Solution Properties and change Any CPU to x86, I think it will do the job.
//Extra currency symbol and currency formatting: "€3,311.50":
String result = (Decimal.Parse("000000331150") / 100).ToString("C");
//No currency symbol and no currency formatting: "3311.50"
String result = (Decimal.Parse("000000331150") / 100).ToString("f2");
Function imageMorph
will create a new img element therefore the id is removed.
Changed to
$("#wrapper > img")
You should use live() function for click event if you want you rocket lanch again.
Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/
You can simply make the top div fixed:
#top { position: fixed; top: 20px; left: 20px; }
The response is an array.
var_dump($pjs[0]->{'player_name'});
This is my solution using only CSS (Jsfiddle: http://jsfiddle.net/xykPT/).
div.options > label > input {_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
div.options > label {_x000D_
display: block;_x000D_
margin: 0 0 0 -10px;_x000D_
padding: 0 0 20px 0; _x000D_
height: 20px;_x000D_
width: 150px;_x000D_
}_x000D_
_x000D_
div.options > label > img {_x000D_
display: inline-block;_x000D_
padding: 0px;_x000D_
height:30px;_x000D_
width:30px;_x000D_
background: none;_x000D_
}_x000D_
_x000D_
div.options > label > input:checked +img { _x000D_
background: url(http://cdn1.iconfinder.com/data/icons/onebit/PNG/onebit_34.png);_x000D_
background-repeat: no-repeat;_x000D_
background-position:center center;_x000D_
background-size:30px 30px;_x000D_
}
_x000D_
<div class="options">_x000D_
<label title="item1">_x000D_
<input type="radio" name="foo" value="0" /> _x000D_
Item 1_x000D_
<img />_x000D_
</label>_x000D_
<label title="item2">_x000D_
<input type="radio" name="foo" value="1" />_x000D_
Item 2_x000D_
<img />_x000D_
</label> _x000D_
<label title="item3">_x000D_
<input type="radio" name="foo" value="2" />_x000D_
Item 3_x000D_
<img />_x000D_
</label>_x000D_
</div>
_x000D_
For those looking for an inline example, here is one:
<audio controls style="width: 200px;">
<source src="http://somewhere.mp3" type="audio/mpeg">
</audio>
It doesn't seem to respect a "height" setting, at least not awesomely. But you can always "customize" the controls but creating your own controls (instead of using the built-in ones) or using somebody's widget that similarly creates its own :)
Always google so you can locate the latest package for both NPP and NPP Plugins.
I googled "notepad++ 64bit". Downloaded the free latest version at Notepad++ (64-bit) - Free download and software. Installed notepad++ by double-click on npp.?.?.?.Installer.x64.exe, installed the .exe to default Windows 64bit path which is, "C:\Program Files".
Then, I googled "notepad++ 64 json viewer plug". Knowing SourceForge.Net is a renowned download site, downloaded JSToolNpp [email protected]. I unzipped and copied JSMinNPP.dll to notePad++ root dir.
I loaded my newly installed notepad++ 64bit. I went to Settings and selected [import plug-in]. I pointed to the location of JSMinNPP.dll and clicked open.
I reloaded notepad++, went to PlugIns menu. To format one-line json string to multi-line json doc, I clicked JSTool->JSFormat or reverse multi-line json doc to one-line json string by JSTool->JSMin (json-Minified)!
Now the class is this
<img src="img/img5.jpg" width="200px" class="rounded-circle float-right">
_x000D_
There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
public class Class1
{
private int CallMe()
{
return 1;
}
}
You can invoke it using this code:
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."
I discovered the Open XML SDK since my original answer. It provides strongly typed classes for spreadsheet objects, among other things, and seems to be fairly easy to work with. I am going to use it for reports in one of my projects. Alas, version 2.0 is not supposed to get released until late 2009 or 2010.
This worked for me:
Rename-Item -Path A_Package.nupkg -NewName A_Package.zip
Expand-Archive -Path A_Package.zip -DestinationPath C:\Reference
I usually do not use any href and change the aspect with css, making them seems link. Thus you do not have to worry about link effect at all, except for the event handler of your application
a {
text-recoration: underline;
cursor: pointer;
}
GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL
. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target.
I usually use: FS-Extra.
const fileNameArray = Fse.readdir('/some/path');
Result:
[
"b7c8a93c-45b3-4de8-b9b5-a0bf28fb986e.jpg",
"daeb1c5b-809f-4434-8fd9-410140789933.jpg"
]
<div style="text-align:center">
<span>Short text</span><br />
<span>This is long text</span>
</div>
I needed an immutable move method (one that didn't change the original array), so I adapted @Reid's accepted answer to simply use Object.assign to create a copy of the array before doing the splice.
Array.prototype.immutableMove = function (old_index, new_index) {
var copy = Object.assign([], this);
if (new_index >= copy.length) {
var k = new_index - copy.length;
while ((k--) + 1) {
copy.push(undefined);
}
}
copy.splice(new_index, 0, copy.splice(old_index, 1)[0]);
return copy;
};
Here is a jsfiddle showing it in action.
Sqlldr wants to write a log file in the same directory where the control file is. But obviously it can't. It probably doesn't have the required permission.
If you're on Linux or Unix, try to run the following command the same way you run sqldr:
touch Billing.log
It will show whether you have the permissions.
Update
The proper command line is:
sqlldr myusername/mypassword control=Billing.ctl
Think of a class as a description of the members of a set of things. All of the members of that set have common characteristics (methods and properties).
A subclass is a class that describes the members of a particular subset of the original set. They share many of characteristics of the main class, but may have properties or methods that are unique to members of the subclass.
You declare that one class is subclass of another via the "extends" keyword in Java.
public class B extends A
{
...
}
B is a subclass of A. Instances of class B will automatically exhibit many of the same properties as instances of class A.
This is the main concept of inheritance in Object-Oriented programming.
Check this example how we could implement this.
public class HoverableDropdownTest {
private WebDriver driver;
private Actions action;
//Edit: there may have been a typo in the '- >' expression (I don't really want to add this comment but SO insist on ">6 chars edit"...
Consumer < By > hover = (By by) -> {
action.moveToElement(driver.findElement(by))
.perform();
};
@Test
public void hoverTest() {
driver.get("https://www.bootply.com/render/6FC76YQ4Nh");
hover.accept(By.linkText("Dropdown"));
hover.accept(By.linkText("Dropdown Link 5"));
hover.accept(By.linkText("Dropdown Submenu Link 5.4"));
hover.accept(By.linkText("Dropdown Submenu Link 5.4.1"));
}
@BeforeTest
public void setupDriver() {
driver = new FirefoxDriver();
action = new Actions(driver);
}
@AfterTest
public void teardownDriver() {
driver.quit();
}
}
For detailed answer, check here - http://www.testautomationguru.com/selenium-webdriver-automating-hoverable-multilevel-dropdowns/
There are now multiple ways to mimic this same effect but further tailor the properties based on the use case. As stated above, this works:
.product__specfield_8_arrow { display: inline-block }
but also
.product__specfield_8_arrow { display: inline-flex } // flex container will be inline
.product__specfield_8_arrow { display: inline-grid } // grid container will be inline
.product__specfield_8_arrow { display: inline-table } // table will be inline-level table
This JSFiddle shows how similar these display properties are in this case.
For a relevant discussion please see this SO post.
Like @g-eorge mention, you can make it like this:
module.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/users/:userId?', {templateUrl: 'template.tpl.html', controller: myCtrl})
}]);
You can also make as much as u need optional parameters.
Here is a Solution for Jupyter and Python3:
I droped my images in a folder named ImageTest
.
My directory is:
C:\Users\MyPcName\ImageTest\image.png
To show the image I used this expression:
![title](/notebooks/ImageTest/image.png "ShowMyImage")
Also watch out for /
and \
If you are using the ThreeTen backport for Android and can't use the newer Date.from(Instant instant)
(which requires minimum of API 26) you can use:
ZonedDateTime zdt = ZonedDateTime.now();
Date date = new Date(zdt.toInstant().toEpochMilli());
or:
Date date = DateTimeUtils.toDate(zdt.toInstant());
Please also read the advice in Basil Bourque's answer
openssl s_client -connect api.cscglobal.com:443 < /dev/null 2>/dev/null | openssl x509 -text -in /dev/stdin | grep "Signature Algorithm" | cut -d ":" -f2 | uniq | sed '/^$/d' | sed -e 's/^[ \t]*//'
Use cut:
cut -d <The character between characters> -f <number of first column>,<number of last column> <file name>
e.g.: If you have file1
containing : car.is.nice.equal.bmw
Run : cut -d . -f1,3 file1
will print car.is.nice
Here's a simple solution, using TypeScript:
convertDateStringToDate(dateStr) {
// Convert a string like '2020-10-04T00:00:00' into '4/Oct/2020'
let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
let date = new Date(dateStr);
let str = date.getDate()
+ '/' + months[date.getMonth()]
+ '/' + date.getFullYear()
return str;
}
(Yeah, I know the question was about JavaScript, but I'm sure I won't be the only Angular developer coming across this article !)
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
The answer of Logan Capaldo is correct but can be marginally simplified because it is unnecessary to specialize the class every time. One can write:
// in header
template<typename T>
struct TypeParseTraits
{ static const char* name; };
// in c-file
#define REGISTER_PARSE_TYPE(X) \
template <> const char* TypeParseTraits<X>::name = #X
REGISTER_PARSE_TYPE(int);
REGISTER_PARSE_TYPE(double);
REGISTER_PARSE_TYPE(FooClass);
// etc...
This also allows you to put the REGISTER_PARSE_TYPE instructions in a C++ file...
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));
They're faster; unless you're loading the entire flat file into memory, a database will allow faster access in almost all cases.
They're safer; databases are easier to safely backup; they have mechanisms to check for file corruption, which flat files do not. Once corruption in your flat file migrates to your backups, you're done, and you might not even know it yet.
They have more features; databases can allow many users to read/write at the same time.
They're much less complex to work with, once they're setup.
Like @Gabi Purcaru mentions above, the proper way to rename and move the file is to use move_uploaded_file()
. It performs some safety checks to prevent security vulnerabilities and other exploits. You'll need to sanitize the value of $_FILES['file']['name']
if you want to use it or an extension derived from it. Use pathinfo
($_FILES['file']['name'], PATHINFO_EXTENSION)
to safely get the extension.
Use MethodInvoker for updating label text in other thread.
private void AggiornaContatore()
{
MethodInvoker inv = delegate
{
this.lblCounter.Text = this.index.ToString();
}
this.Invoke(inv);
}
You are getting the error because your UI thread is holding the label, and since you are trying to update it through another thread you are getting cross thread exception.
You may also see: Threading in Windows Forms
If the values came from another table, you might want to use
UPDATE table1 t1
SET (col1, col2) = (
SELECT col3, col4
FROM table2 t2
WHERE t1.col8=t2.col9
)
Example:
UPDATE table1
SET (col1, col2, col3) =(
(SELECT MIN (ship_charge), MAX (ship_charge) FROM orders),
'07/01/2007'
)
WHERE col4 = 1001;
Are you using the HTML5 required attribute?
That will cause Chrome 10 to display a balloon prompting the user to fill out the field.
Here is my implementation for your reference:
def _mkdir_recursive(self, path):
sub_path = os.path.dirname(path)
if not os.path.exists(sub_path):
self._mkdir_recursive(sub_path)
if not os.path.exists(path):
os.mkdir(path)
Hope this help!
You can probably start a Service
here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.
UDPATE
You can use START_STICKY
to make your Service running continuously.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
You can adjust the plot margins with plot.margin
in theme()
and then move your axis labels and title with the vjust
argument of element_text()
. For example :
library(ggplot2)
library(grid)
qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.title.x=element_text(vjust=-2)) +
theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
theme(plot.title=element_text(size=15, vjust=3)) +
theme(plot.margin = unit(c(1,1,1,1), "cm"))
will give you something like this :
If you want more informations about the different theme()
parameters and their arguments, you can just enter ?theme
at the R prompt.
Thiago answer is correct, adding sample more specific to question, @ElementCollection will create new table in your database, but without mapping two tables, It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a collection of embeddable elements (class annotated with @Embeddable).
Here is the sample to persist list of String
@ElementCollection
private Collection<String> options = new ArrayList<String>();
Here is the sample to persist list of Custom object
@Embedded
@ElementCollection
private Collection<Car> carList = new ArrayList<Car>();
For this case we need to make class Embeddable
@Embeddable
public class Car {
}
Pros: Host on Google has benefits
Cons:
I wonder if you can INCLUDE from Google, and then check the presence of some Global variable, or somesuch, and if absence load from your server?
If your Vim is not compiled with clipboards, you wish to copy selected text instead of entire lines, you do not want to install MacVim or other GUI, the simplest solution is to add this line to your .vimrc:
map <C-c> y:e ~/clipsongzboard<CR>P:w !pbcopy<CR><CR>:bdelete!<CR>
To use it, simply visually select the text you want to copy, and then Control-C. If you want a full explanation of this line read "How to Copy to clipboard on vim".
I was just banging my head against a wall just trying to get S3 uploads to work with large files. Initially my error was:
An error occurred (AccessDenied) when calling the CreateMultipartUpload operation: Access Denied
Then I tried copying a smaller file and got:
An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
I could list objects fine but I couldn't do anything else even though I had s3:*
permissions in my Role policy. I ended up reworking the policy to this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject"
],
"Resource": "arn:aws:s3:::my-bucket/*"
},
{
"Effect": "Allow",
"Action": [
"s3:ListBucketMultipartUploads",
"s3:AbortMultipartUpload",
"s3:ListMultipartUploadParts"
],
"Resource": [
"arn:aws:s3:::my-bucket",
"arn:aws:s3:::my-bucket/*"
]
},
{
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "*"
}
]
}
Now I'm able to upload any file. Replace my-bucket
with your bucket name. I hope this helps somebody else that's going thru this.
An expression is something that can be reduced to a value, for example "1+3"
is an expression, but "foo = 1+3"
is not.
It's easy to check:
print(foo = 1+3)
If it doesn't work, it's a statement, if it does, it's an expression.
Another statement could be:
class Foo(Bar): pass
as it cannot be reduced to a value.
Typically, once a browser has asked the user for credentials and supplied them to a particular web site, it will continue to do so without further prompting. Unlike the various ways you can clear cookies on the client side, I don't know of a similar way to ask the browser to forget its supplied authentication credentials.
Here is the batch file which should work for you:
@echo off
Title HOST: Installing updates on %computername%
echo %computername%
set Server=\\SERVERNAME or PATH\msifolder
:select
cls
echo Select one of the following MSI install folders for installation task.
echo.
dir "%Server%" /AD /ON /B
echo.
set /P "MSI=Please enter the MSI folder to install: "
set "Package=%Server%\%MSI%\%MSI%.msi"
if not exist "%Package%" (
echo.
echo The entered folder/MSI file does not exist ^(typing mistake^).
echo.
setlocal EnableDelayedExpansion
set /P "Retry=Try again [Y/N]: "
if /I "!Retry!"=="Y" endlocal & goto select
endlocal
goto :EOF
)
echo.
echo Selected installation: %MSI%
echo.
echo.
:verify
echo Is This Correct?
echo.
echo.
echo 0: ABORT INSTALL
echo 1: YES
echo 2: NO, RE-SELECT
echo.
set /p "choice=Select YES, NO or ABORT? [0,1,2]: "
if [%choice%]==[0] goto :EOF
if [%choice%]==[1] goto yes
goto select
:yes
echo.
echo Running %MSI% installation ...
start "Install MSI" /wait "%SystemRoot%\system32\msiexec.exe" /i /quiet "%Package%"
The characters listed on last page output on entering in a command prompt window either help cmd
or cmd /?
have special meanings in batch files. Here are used parentheses and square brackets also in strings where those characters should be interpreted literally. Therefore it is necessary to either enclose the string in double quotes or escape those characters with character ^
as it can be seen in code above, otherwise command line interpreter exits batch execution because of a syntax error.
And it is not possible to call a file with extension MSI. A *.msi file is not an executable. On double clicking on a MSI file, Windows looks in registry which application is associated with this file extension for opening action. And the application to use is msiexec
with the command line option /i
to install the application inside MSI package.
Run msiexec.exe /?
to get in a GUI window the available options or look at Msiexec (command-line options).
I have added already /quiet
additionally to required option /i
for a silent installation.
In batch code above command start
is used with option /wait
to start Windows application msiexec.exe
and hold execution of batch file until installation finished (or aborted).
You mention batch files, am I correct then assuming that you're talking about a Windows system? If so you cannot use sshpass, and you will have to switch to a different option.
Two of such options, that follow diametrically opposite philosophies are:
Either way, switching from password to PKI authentication is strongly recommended.
You could also use the .add()
function:
df.loc[:,'variance'] = df.loc[:,'budget'].add(df.loc[:,'actual'])
If you want to move an annotated tag, changing only the targeted commit but preserving the annotation message and other metadata use:
moveTag() {
local tagName=$1
# Support passing branch/tag names (not just full commit hashes)
local newTarget=$(git rev-parse $2^{commit})
git cat-file -p refs/tags/$tagName |
sed "1 s/^object .*$/object $newTarget/g" |
git hash-object -w --stdin -t tag |
xargs -I {} git update-ref refs/tags/$tagName {}
}
usage: moveTag <tag-to-move> <target>
The above function was developed by referencing teerapap/git-move-annotated-tag.sh.
In my case, simply giving the user permissions on the database fixed it.
So Right click on the database -> Click Properties -> [left hand menu] Click Permissions -> and scroll down to Backup database -> Tick "Grant"
OK - so this issue has been driving me crazy - v 6.3.6 on Ubuntu Linux. None of the above solutions worked for me. Connecting to localhost mysql server previously always worked fine. Connecting to remote server always timed out - after about 60 seconds, sometimes after less time, sometimes more.
What finally worked for me was upgrading Workbench to 6.3.9 - no more dropped connections.
We've seen in our projects that a post request with JSON and files is creating a lot of confusion between the frontend and backend developers, leading to unnecessary wastage of time.
Here's a better approach: convert file bytes array to Base64 string and send it in the JSON.
public Class UserDTO {
private String firstName;
private String lastName;
private FileDTO profilePic;
}
public class FileDTO {
private String base64;
// just base64 string is enough. If you want, send additional details
private String name;
private String type;
private String lastModified;
}
@PostMapping("/user")
public String saveUser(@RequestBody UserDTO user) {
byte[] fileBytes = Base64Utils.decodeFromString(user.getProfilePic().getBase64());
....
}
JS code to convert file to base64 string:
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
const userDTO = {
firstName: "John",
lastName: "Wick",
profilePic: {
base64: reader.result,
name: file.name,
lastModified: file.lastModified,
type: file.type
}
}
// post userDTO
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
My solution was extremely close to Joel's (Not Etherton, just plain Joel):
public partial class WaitingDialog : Form
{
public WaitingDialog()
{
InitializeComponent();
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BackColor = Color.Transparent;
this.TransparencyKey = Color.Transparent; // I had to add this to get it to work.
// Other stuff
}
protected override void OnPaintBackground(PaintEventArgs e) { /* Ignore */ }
}
Try this:
@Override
public void onBackPressed() {
finish();
}
MY example . DoWork is below:
DoLengthyWork();
//this is never executed
if(bgWorker.CancellationPending)
{
MessageBox.Show("Up to here? ...");
e.Cancel = true;
}
inside DoLenghtyWork :
public void DoLenghtyWork()
{
OtherStuff();
for(int i=0 ; i<10000000; i++)
{ int j = i/3; }
}
inside OtherStuff() :
public void OtherStuff()
{
for(int i=0 ; i<10000000; i++)
{ int j = i/3; }
}
What you want to do is modify both DoLenghtyWork and OtherStuff() so that they become:
public void DoLenghtyWork()
{
if(!bgWorker.CancellationPending)
{
OtherStuff();
for(int i=0 ; i<10000000; i++)
{
int j = i/3;
}
}
}
public void OtherStuff()
{
if(!bgWorker.CancellationPending)
{
for(int i=0 ; i<10000000; i++)
{
int j = i/3;
}
}
}
eloone did it file by file with
git checkout <commit-hash> <filename>
but you could checkout all files more easily by doing
git checkout <commit-hash> .
return results==null ? 0 : ( results[1] || 0 );
There are three states of button
button
button:hover
button:active
Normal:
.button
{
//your css
}
Active
.button:active
{
//your css
}
Hover
.button:hover
{
//your css
}
SNIPPET:
Use :active
to style the active state of button.
button:active{_x000D_
background-color:red;_x000D_
}
_x000D_
<button>Click Me</button>
_x000D_