I don't know about MySQL, but in MS SQL, you can use the column index in the order by
clause. I've done this before when doing counts with group by
s as it tends to be easier to work with.
So
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20
Becomes
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER 1 DESC
LIMIT 20
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
Disclaimer: this is the Swift
version of how to create a delegate
.
So, what are delegates? …in software development, there are general reusable solution architectures that help to solve commonly occurring problems within a given context, these “templates”, so to speak, are best known as design patterns. Delegates are a design pattern that allows one object to send messages to another object when a specific event happens. Imagine an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action, this can be achieved with the help of delegates!
For a better explanation, I am going to show you how to create a custom delegate that passes data between classes, with Swift in a simple application,start by downloading or cloning this starter project and run it!
You can see an app with two classes, ViewController A
and ViewController B
. B has two views that on tap changes the background color of the ViewController
, nothing too complicated right? well now let’s think in an easy way to also change the background color of class A when the views on class B are tapped.
The problem is that this views are part of class B and have no idea about class A, so we need to find a way to communicate between this two classes, and that’s where delegation shines. I divided the implementation into 6 steps so you can use this as a cheat sheet when you need it.
step 1: Look for the pragma mark step 1 in ClassBVC file and add this
//MARK: step 1 Add Protocol here.
protocol ClassBVCDelegate: class {
func changeBackgroundColor(_ color: UIColor?)
}
The first step is to create a protocol
, in this case, we will create the protocol in class B, inside the protocol you can create as many functions that you want based on the requirements of your implementation. In this case, we just have one simple function that accepts an optional UIColor
as an argument.
Is a good practice to name your protocols adding the word delegate
at the end of the class name, in this case, ClassBVCDelegate
.
step 2: Look for the pragma mark step 2 in ClassVBC
and add this
//MARK: step 2 Create a delegate property here.
weak var delegate: ClassBVCDelegate?
Here we just create a delegate property for the class, this property must adopt the protocol
type, and it should be optional. Also, you should add the weak keyword before the property to avoid retain cycles and potential memory leaks, if you don’t know what that means don’t worry for now, just remember to add this keyword.
step 3: Look for the pragma mark step 3 inside the handleTap method
in ClassBVC
and add this
//MARK: step 3 Add the delegate method call here.
delegate?.changeBackgroundColor(tapGesture.view?.backgroundColor)
One thing that you should know, run the app and tap on any view, you won’t see any new behavior and that’s correct but the thing that I want to point out is that the app it’s not crashing when the delegate is called, and it’s because we create it as an optional value and that’s why it won’t crash even the delegated doesn’t exist yet. Let’s now go to ClassAVC
file and make it, the delegated.
step 4: Look for the pragma mark step 4 inside the handleTap method in ClassAVC
and add this next to your class type like this.
//MARK: step 4 conform the protocol here.
class ClassAVC: UIViewController, ClassBVCDelegate {
}
Now ClassAVC adopted the ClassBVCDelegate
protocol, you can see that your compiler is giving you an error that says “Type ‘ClassAVC does not conform to protocol ‘ClassBVCDelegate’ and this only means that you didn’t use the methods of the protocol yet, imagine that when class A adopts the protocol is like signing a contract with class B and this contract says “Any class adopting me MUST use my functions!”
Quick note: If you come from an Objective-C
background you are probably thinking that you can also shut up that error making that method optional, but for my surprise, and probably yours, Swift
language does not support optional protocols
, if you want to do it you can create an extension for your protocol
or use the @objc keyword in your protocol
implementation.
Personally, If I have to create a protocol with different optional methods I would prefer to break it into different protocols
, that way I will follow the concept of giving one single responsibility to my objects, but it can vary based on the specific implementation.
here is a good article about optional methods.
step 5: Look for the pragma mark step 5 inside the prepare for segue method and add this
//MARK: step 5 create a reference of Class B and bind them through the `prepareforsegue` method.
if let nav = segue.destination as? UINavigationController, let classBVC = nav.topViewController as? ClassBVC {
classBVC.delegate = self
}
Here we are just creating an instance of ClassBVC
and assign its delegate to self, but what is self here? well, self is the ClassAVC
which has been delegated!
step 6: Finally, look for the pragma step 6 in ClassAVC
and let’s use the functions of the protocol
, start typing func changeBackgroundColor and you will see that it’s auto-completing it for you. You can add any implementation inside it, in this example, we will just change the background color, add this.
//MARK: step 6 finally use the method of the contract
func changeBackgroundColor(_ color: UIColor?) {
view.backgroundColor = color
}
Now run the app!
Delegates
are everywhere and you probably use them without even notice, if you create a tableview
in the past you used delegation, many classes of UIKIT
works around them and many other frameworks
too, they solve these main problems.
Congratulations, you just implement a custom delegate, I know that you are probably thinking, so much trouble just for this? well, delegation is a very important design pattern to understand if you want to become an iOS
developer, and always keep in mind that they have one to one relationship between objects.
You can see the original tutorial here
Here is perhaps the simplest way to obtain the value of a single cell.
document.querySelector("#table").children[0].children[r].children[c].innerText
where r is the row index and c is the column index
Therefore, to obtain all cell data and put it in a multi-dimensional array:
var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].
Perl versions 5.10 and later support subsidiary vertical and horizontal character classes, \v
and \h
, as well as the generic whitespace character class \s
The cleanest solution is to use the horizontal whitespace character class \h
. This will match tab and space from the ASCII set, non-breaking space from extended ASCII, or any of these Unicode characters
U+0009 CHARACTER TABULATION
U+0020 SPACE
U+00A0 NO-BREAK SPACE (not matched by \s)
U+1680 OGHAM SPACE MARK
U+2000 EN QUAD
U+2001 EM QUAD
U+2002 EN SPACE
U+2003 EM SPACE
U+2004 THREE-PER-EM SPACE
U+2005 FOUR-PER-EM SPACE
U+2006 SIX-PER-EM SPACE
U+2007 FIGURE SPACE
U+2008 PUNCTUATION SPACE
U+2009 THIN SPACE
U+200A HAIR SPACE
U+202F NARROW NO-BREAK SPACE
U+205F MEDIUM MATHEMATICAL SPACE
U+3000 IDEOGRAPHIC SPACE
The vertical space pattern \v
is less useful, but matches these characters
U+000A LINE FEED
U+000B LINE TABULATION
U+000C FORM FEED
U+000D CARRIAGE RETURN
U+0085 NEXT LINE (not matched by \s)
U+2028 LINE SEPARATOR
U+2029 PARAGRAPH SEPARATOR
There are seven vertical whitespace characters which match \v
and eighteen horizontal ones which match \h
. \s
matches twenty-three characters
All whitespace characters are either vertical or horizontal with no overlap, but they are not proper subsets because \h
also matches U+00A0 NO-BREAK SPACE, and \v
also matches U+0085 NEXT LINE, neither of which are matched by \s
In Ubuntu I noticed there are 2 files. The real one is /etc/init.d/rc.local
; it seems the other /etc/rc.local
is bogus?
Once I modified the correct one (/etc/init.d/rc.local
) it did execute just as expected.
From a comment:
I want to sort each set.
That's easy. For any set s
(or anything else iterable), sorted(s)
returns a list of the elements of s
in sorted order:
>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']
Note that sorted
is giving you a list
, not a set
. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2}
and {2, 1}
are the same set.
You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).
The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key
function:
>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']
For more information, see the Sorting HOWTO in the official docs.
* See the comments for exceptions.
You have to validate the connection.
If you use Oracle it is likely that you use Oracle´s Universal Connection Pool. The following assumes that you do so.
The easiest way to validate the connection is to tell Oracle that the connection must be validated while borrowing it. This can be done with
pool.setValidateConnectionOnBorrow(true);
But it works only if you hold the connection for a short period. If you borrow the connection for a longer time, it is likely that the connection gets broken while you hold it. In that case you have to validate the connection explicitly with
if (connection == null || !((ValidConnection) connection).isValid())
See the Oracle documentation for further details.
For future reference:
This is typically an error that occurs when you are unable to view or execute the file, the reason for which is generally a permissions error. I would start by following @Renning 's suggestion and running chmod 755 test.cgi
(obviously replace test.cgi with the name of your cgi script here).
If that doesn't work there are a couple other things you can try. I once got this error when I created test.cgi
as root in another user's home. The fix there was to run chmod user:user test.cgi
where user is the name of the user who's home you're in.
The last thing I can think of is making sure that your cgi script is returning the proper headers. In my ruby script I did it by putting puts "Content-type: text/html"
before I actually outputted anything to the page.
Happy coding!
You can compare an array like the below mentioned if the array has some values
it('should check if the array are equal', function() {
var mockArr = [1, 2, 3];
expect(mockArr ).toEqual([1, 2, 3]);
});
But if the array that is returned from some function has more than 1 elements and all are zero then verify by using
expect(mockArray[0]).toBe(0);
I think you can do this with the hyperref
package, although I've not tried it myself. From the relevant LaTeX Wikibook section:
The
hyperref
package introduces another useful command;\autoref{}
. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command\autoref{sec:intro}
would create a hyperlink to the\label{sec:intro}
command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining\typeautorefname
to the prefix you want, as in:
\def\subsectionautorefname{section}
players
is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:
name, score = player
(if the player
list is always a constant length).
There's not much more advice we can give you without knowing what query
is and how it works.
It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError
on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.
The $ sign is an identifier for variables and functions.
That has a clear explanation of what the dollar sign is for.
Here's an alternative explanation: http://www.vcarrer.com/2010/10/about-dollar-sign-in-javascript.html
You could also use:
$ mvn release:update-versions -DdevelopmentVersion={version}
to update the version numbers in your POMs.
Ross has the right idea for POSTing the usual parameter/value format to a url.
I recently ran into a situation where I needed to POST some XML as Content-Type "text/xml" without any parameter pairs so here's how you do that:
$xml = '<?xml version="1.0"?><stuff><child>foo</child><child>bar</child></stuff>';
$httpRequest = curl_init();
curl_setopt($httpRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($httpRequest, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($httpRequest, CURLOPT_POST, 1);
curl_setopt($httpRequest, CURLOPT_HEADER, 1);
curl_setopt($httpRequest, CURLOPT_URL, $url);
curl_setopt($httpRequest, CURLOPT_POSTFIELDS, $xml);
$returnHeader = curl_exec($httpRequest);
curl_close($httpRequest);
In my case, I needed to parse some values out of the HTTP response header so you may not necessarily need to set CURLOPT_RETURNTRANSFER
or CURLOPT_HEADER
.
Unfortunately, there is no guaranteed way to do it at time of selection.
Some browsers support the accept
attribute for input
tags. This is a good start, but cannot be relied upon completely.
<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
You can use a cfinput
and run a validation to check the file extension at submission, but not the mime-type. This is better, but still not fool-proof. Files on OSX often have no file extensions or users could maliciously mislabel the file types.
ColdFusion's cffile
can check the mime-type using the contentType
property of the result (cffile.contentType
), but that can only be done after the upload. This is your best bet, but is still not 100% safe as mime-types could still be wrong.
In this world of flashy new native functions, we sometimes forget the basics.
for (let i = 0; i < arr.length; i++) {
console.log('index:', i, 'element:', arr[i]);
}
Clean, efficient, and you can still break
the loop. Bonus! You can also start from the end and go backwards with i--
!
Additional note: If you're using the value a lot within the loop, you may wish to do const value = arr[i];
at the top of the loop for an easy, readable reference.
Jbuilder is a gem built by rails community. But it works well in non-rails environments and have a cool set of features.
# suppose we have a sample object as below
sampleObj.name #=> foo
sampleObj.last_name #=> bar
# using jbuilder we can convert it to json:
Jbuilder.encode do |json|
json.name sampleObj.name
json.last_name sampleObj.last_name
end #=> "{:\"name\" => \"foo\", :\"last_name\" => \"bar\"}"
See Redirecting Output from a Running Process.
Firstly I run the command
cat > foo1
in one session and test that data from stdin is copied to the file. Then in another session I redirect the output.Firstly find the PID of the process:
$ ps aux | grep cat rjc 6760 0.0 0.0 1580 376 pts/5 S+ 15:31 0:00 cat
Now check the file handles it has open:
$ ls -l /proc/6760/fd total 3 lrwx—— 1 rjc rjc 64 Feb 27 15:32 0 -> /dev/pts/5 l-wx—— 1 rjc rjc 64 Feb 27 15:32 1 -> /tmp/foo1 lrwx—— 1 rjc rjc 64 Feb 27 15:32 2 -> /dev/pts/5
Now run GDB:
$ gdb -p 6760 /bin/cat GNU gdb 6.4.90-debian [license stuff snipped] Attaching to program: /bin/cat, process 6760 [snip other stuff that's not interesting now] (gdb) p close(1) $1 = 0 (gdb) p creat("/tmp/foo3", 0600) $2 = 1 (gdb) q The program is running. Quit anyway (and detach it)? (y or n) y Detaching from program: /bin/cat, process 6760
The
p
command in GDB will print the value of an expression, an expression can be a function to call, it can be a system call… So I execute aclose()
system call and pass file handle 1, then I execute acreat()
system call to open a new file. The result of thecreat()
was 1 which means that it replaced the previous file handle. If I wanted to use the same file for stdout and stderr or if I wanted to replace a file handle with some other number then I would need to call thedup2()
system call to achieve that result.For this example I chose to use
creat()
instead ofopen()
because there are fewer parameter. The C macros for the flags are not usable from GDB (it doesn’t use C headers) so I would have to read header files to discover this – it’s not that hard to do so but would take more time. Note that 0600 is the octal permission for the owner having read/write access and the group and others having no access. It would also work to use 0 for that parameter and run chmod on the file later on.After that I verify the result:
ls -l /proc/6760/fd/ total 3 lrwx—— 1 rjc rjc 64 2008-02-27 15:32 0 -> /dev/pts/5 l-wx—— 1 rjc rjc 64 2008-02-27 15:32 1 -> /tmp/foo3 <==== lrwx—— 1 rjc rjc 64 2008-02-27 15:32 2 -> /dev/pts/5
Typing more data in to
cat
results in the file/tmp/foo3
being appended to.If you want to close the original session you need to close all file handles for it, open a new device that can be the controlling tty, and then call
setsid()
.
Combining the following sources, the following code works on Windows, Linux and macOS using just the platform
and os
modules:
tx = input("Text to say >>> ")
tx = repr(tx)
import os
import platform
syst = platform.system()
if syst == 'Linux' and platform.linux_distribution()[0] == "Ubuntu":
os.system('spd-say %s' % tx)
elif syst == 'Windows':
os.system('PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(%s);"' % tx)
elif syst == 'Darwin':
os.system('say %s' % tx)
else:
raise RuntimeError("Operating System '%s' is not supported" % syst)
Note: This method is not secure and could be exploited by malicious text.
This works for getting UTC milliseconds in Android.
Calendar c = Calendar.getInstance();
int utcOffset = c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET);
Long utcMilliseconds = c.getTimeInMillis() + utcOffset;
Query string parameters can be accepted simply by using an argument on the action - i.e.
public ActionResult Foo(string someValue, int someOtherValue) {...}
which will accept a query like .../someroute?someValue=abc&someOtherValue=123
Other than that, you can look at the request directly for more control.
Here is an option I found to export to Excel (can be modified for CSV I believe)
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
I know my answer is 7 years late, but here's my suggestion anyway:
When Access complains about an UPDATE query that includes a JOIN, just save the query, with RecordsetType
property set to Dynaset (Inconsistent Updates)
.
This will sometimes allow the UPDATE to work.
I keep coming back to these questions trying to figure out where exactly the data I'm interested in is buried in what is truly a monolithic ErrorRecord structure. Almost all answers give piecemeal instructions on how to pull certain bits of data.
But I've found it immensely helpful to dump the entire object with ConvertTo-Json
so that I can visually see LITERALLY EVERYTHING in a comprehensible layout.
try {
Invoke-WebRequest...
}
catch {
Write-Host ($_ | ConvertTo-Json)
}
Use ConvertTo-Json
's -Depth
parameter to expand deeper values, but use extreme caution going past the default depth of 2
:P
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json
Context is stored at the application level scope where as request is stored at page level i.e to say
Web Container brings up the applications one by one and run them inside its JVM. It stores a singleton object in its jvm where it registers anyobject that is put inside it.This singleton is shared across all applications running inside it as it is stored inside the JVM of the container itself.
However for requests, the container creates a request object that is filled with data from request and is passed along from one thread to the other (each thread is a new request that is coming to the server), also request is passed to the threads of same application.
Use the update flag: -u
Example:
zip -ur existing.zip myFolder
This command will compress and add myFolder
(and it's contents) to the existing.zip
.
Advanced Usage:
The update flag actually compares the incoming files against the existing ones and will either add new files, or update existing ones.
Therefore, if you want to add/update a specific subdirectory within the zip file, just update the source as desired, and then re-zip the entire source with the -u
flag. Only the changed files will be zipped.
If you don't have access to the source files, you can unzip the zip file, then update the desired files, and then re-zip with the -u
flag. Again, only the changed files will be zipped.
Example:
Original Source Structure
ParentDir
+-- file1.txt
+-- file2.txt
+-- ChildDir
¦ +-- file3.txt
¦ +-- Logs
¦ ¦ +-- logs1.txt
¦ ¦ +-- logs2.txt
¦ ¦ +-- logs3.txt
Updated Source Structure
ParentDir
+-- file1.txt
+-- file2.txt
+-- ChildDir
¦ +-- file3.txt
¦ +-- Logs
¦ ¦ +-- logs1.txt
¦ ¦ +-- logs2.txt
¦ ¦ +-- logs3.txt
¦ ¦ +-- logs4.txt <-- NEW FILE
Usage
$ zip -ur existing.zip ParentDir
> updating: ParentDir/ChildDir/Logs (stored 0%)
> adding: ParentDir/ChildDir/Logs/logs4.txt (stored 96%)
I know there are a lot of answers here already, but none of them helped me. In the end I opened the file /etc/elasticsearch/jvm.options
and changed:
-Xms2G
-Xmx2G
to
-Xms256M
-Xmx256M
That solved it for me. Hopefully this helps someone else here.
If you want to use a high-level API, that hides a lot of the JDBC complexity around database schema metadata, take a look at this article: http://www.devx.com/Java/Article/32443/1954
Suppose you have less data, I suggest to try 70%, 80% and 90% and test which is giving better result. In case of 90% there are chances that for 10% test you get poor accuracy.
Worked for me. To set drawable at the right
tvBioLive.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close_red_400_24dp, 0)
If you don't have readlink or realpath utilities than you can use following function which works in bash and zsh (not sure about the rest).
abspath () { case "$1" in /*)printf "%s\n" "$1";; *)printf "%s\n" "$PWD/$1";; esac; }
This also works for nonexistent files (as does the python function os.path.abspath
).
Unfortunately abspath ./../somefile
doesn't get rid of the dots.
After trying almost every key on my keyboard:
C:\Users\Tim>cd ^
Mehr? Desktop
C:\Users\Tim\Desktop>
So it seems to be the ^ key.
barplot(data)
barplot(data, yaxp=c(0, max(data), 5))
yaxp=c(minY-axis, maxY-axis, Interval)
Enough explanation about each parameter is given by other answers; However you asked for a real world example, here is the one that clarifies the purpose of different propagation options:
Suppose you're in charge of implementing a signup service in which a confirmation e-mail is sent to the user. You come up with two service objects, one for enrolling the user and one for sending e-mails, which the latter is called inside the first one. For example something like this:/* Sign Up service */
@Service
@Transactional(Propagation=REQUIRED)
class SignUpService{
...
void SignUp(User user){
...
emailService.sendMail(User);
}
}
/* E-Mail Service */
@Service
@Transactional(Propagation=REQUIRES_NEW)
class EmailService{
...
void sendMail(User user){
try{
... // Trying to send the e-mail
}catch( Exception)
}
}
You may have noticed that the second service is of propagation type REQUIRES_NEW and moreover chances are it throws an exception (SMTP server down ,invalid e-mail or other reasons).You probably don't want the whole process to roll-back, like removing the user information from database or other things; therefore you call the second service in a separate transaction.
Back to our example, this time you are concerned about the database security, so you define your DAO classes this way:/* User DAO */
@Transactional(Propagation=MANDATORY)
class UserDAO{
// some CRUD methods
}
Meaning that whenever a DAO object, and hence a potential access to db, is created, we need to reassure that the call was made from inside one of our services, implying that a live transaction should exist; otherwise an exception occurs.Therefore the propagation is of type MANDATORY.
While personally I would be preferring !str.isBlank()
, as others already suggested (or str -> !str.isBlank()
as a Predicate), a more modern and efficient version of the str.trim()
approach mentioned above, would be using str.strip()
- considering nulls as "whitespace":
if (str != null && str.strip().length() > 0) {...}
For example as Predicate, for use with streams, e. g. in a unit test:
@Test
public void anyNonEmptyStrippedTest() {
String[] strings = null;
Predicate<String> isNonEmptyStripped = str -> str != null && str.strip().length() > 0;
assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).noneMatch(isNonEmptyStripped)).orElse(true));
strings = new String[] { null, "", " ", "\\n", "\\t", "\\r" };
assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).anyMatch(isNonEmptyStripped)).orElse(true));
strings = new String[] { null, "", " ", "\\n", "\\t", "\\r", "test" };
}
I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:
Request.AddHeader "Content-Type", "application/json"
Here is the snippet of my code:
Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String
Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac
Set Response = Client.Execute(Request)
To create a 'connection' between SeekBar
and MediaPlayer
you need first to get your current recording max duration and set it to your seek bar.
mSeekBar.setMax(mFileDuration/1000); // where mFileDuration is mMediaPlayer.getDuration();
After you initialise your MediaPlayer
and for example press play button, you should create handler and post runnable so you can update your SeekBar
(in the UI thread
itself) with the current position of your MediaPlayer
like this :
private Handler mHandler = new Handler();
//Make sure you update Seekbar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if(mMediaPlayer != null){
int mCurrentPosition = mMediaPlayer.getCurrentPosition() / 1000;
mSeekBar.setProgress(mCurrentPosition);
}
mHandler.postDelayed(this, 1000);
}
});
and update that value every second.
If you need to update the MediaPlayer
's position while user drag your SeekBar
you should add OnSeekBarChangeListener
to your SeekBar
and do it there :
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mMediaPlayer != null && fromUser){
mMediaPlayer.seekTo(progress * 1000);
}
}
});
And that should do the trick! : )
EDIT: One thing which I've noticed in your code, don't do :
public MainActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
make all initialisations in your onCreate();
, do not create constructors of your Activity
.
I think you've actually got a wider confusion here.
The initial error is that you're trying to call split
on the whole list of lines, and you can't split
a list of strings, only a string. So, you need to split
each line, not the whole thing.
And then you're doing for points in Type
, and expecting each such points
to give you a new x
and y
. But that isn't going to happen. Types
is just two values, x
and y
, so first points
will be x
, and then points will be y
, and then you'll be done. So, again, you need to loop over each line and get the x
and y
values from each line, not loop over a single Types
from a single line.
So, everything has to go inside a loop over every line in the file, and do the split
into x
and y
once for each line. Like this:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
for line in readfile:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
getQuakeData()
As a side note, you really should close
the file, ideally with a with
statement, but I'll get to that at the end.
Interestingly, the problem here isn't that you're being too much of a newbie, but that you're trying to solve the problem in the same abstract way an expert would, and just don't know the details yet. This is completely doable; you just have to be explicit about mapping the functionality, rather than just doing it implicitly. Something like this:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = readfile.readlines()
Types = [line.split(",") for line in readlines]
xs = [Type[1] for Type in Types]
ys = [Type[2] for Type in Types]
for x, y in zip(xs, ys):
print(x,y)
getQuakeData()
Or, a better way to write that might be:
def getQuakeData():
filename = input("Please enter the quake file: ")
# Use with to make sure the file gets closed
with open(filename, "r") as readfile:
# no need for readlines; the file is already an iterable of lines
# also, using generator expressions means no extra copies
types = (line.split(",") for line in readfile)
# iterate tuples, instead of two separate iterables, so no need for zip
xys = ((type[1], type[2]) for type in types)
for x, y in xys:
print(x,y)
getQuakeData()
Finally, you may want to take a look at NumPy and Pandas, libraries which do give you a way to implicitly map functionality over a whole array or frame of data almost the same way you were trying to.
Convert them into dates or timestamp integers and then just check of $date_from_user is <= $end_date and >= $start_date
This terminal command:
open /Applications/Python\ 3.7/Install\ Certificates.command
Found here: https://stackoverflow.com/a/57614113/6207266
Resolved it for me. With my config
pip install --upgrade certifi
had no impact.
I have two recommendation for you
-Drevision=2.0.1
in .mvn/maven.config
file. So basically you define your version only at one location.As Selman22 said, you are overriding the default object.Equals
method, which accepts an object obj
and not a safe compile time type.
In order for that to happen, make your type implement IEquatable<Box>
:
public class Box : IEquatable<Box>
{
double height, length, breadth;
public static bool operator ==(Box obj1, Box obj2)
{
if (ReferenceEquals(obj1, obj2))
{
return true;
}
if (ReferenceEquals(obj1, null))
{
return false;
}
if (ReferenceEquals(obj2, null))
{
return false;
}
return obj1.Equals(obj2);
}
public static bool operator !=(Box obj1, Box obj2)
{
return !(obj1 == obj2);
}
public bool Equals(Box other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return height.Equals(other.height)
&& length.Equals(other.length)
&& breadth.Equals(other.breadth);
}
public override bool Equals(object obj)
{
return Equals(obj as Box);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = height.GetHashCode();
hashCode = (hashCode * 397) ^ length.GetHashCode();
hashCode = (hashCode * 397) ^ breadth.GetHashCode();
return hashCode;
}
}
}
Another thing to note is that you are making a floating point comparison using the equality operator and you might experience a loss of precision.
You can use this implementation that ExecutorService provides
invokeAll(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit)
as
executor.invokeAll(Arrays.asList(task), 2 , TimeUnit.SECONDS);
However, in my case, I could not as Arrays.asList took extra 20ms.
just wanted to leave my .scss
example here, I think its kinda best practice, especially I think if you do customization its nice to set the width only once! It is not clever to apply it everywhere, you will increase the human factor exponentially.
Im looking forward for your feedback!
// Set your parameters
$widthSmall: 768px;
$widthMedium: 992px;
// Prepare your "function"
@mixin in-between {
@media (min-width:$widthSmall) and (max-width:$widthMedium) {
@content;
}
}
// Apply your "function"
main {
@include in-between {
//Do something between two media queries
padding-bottom: 20px;
}
}
EDIT: Updated for jQuery 1.8
Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
it looks something like this :
Swift 3 solution:
let singleTap = UITapGestureRecognizer(target: self, action:#selector(self.singleTapAction(_:)))
singleTap.numberOfTapsRequired = 1
view.addGestureRecognizer(singleTap)
let doubleTap = UITapGestureRecognizer(target: self, action:#selector(self.doubleTapAction(_:)))
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)
singleTap.require(toFail: doubleTap)
In the code line singleTap.require(toFail: doubleTap) we are forcing the single tap to wait and ensure that the tap event is not a double tap.
Your code is passing a function as an argument to find
. That function takes an element
argument (of type Conversation
) and returns void
(meaning there is no return value). TypeScript describes this as (element: Conversation) => void'
What TypeScript is saying is that the find
function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations
, a number
and a Conversation
array, and that this function should return a boolean
.
So bottom line is that you either need to change your code to pass in the values to find
correctly, or else you need to provide an overload to the definition of find
in your definition file that accepts a Conversation
and returns void
.
When docker kill CONTAINER_ID
does not work and docker stop -t 1 CONTAINER_ID
also does not work, you can try to delete the container:
docker container rm CONTAINER_ID
I had a similar issue today where containers were in a continuous restart loop.
The issue in my case was related to me being a poor engineer.
Anyway, I fixed the issue by deleting the container, fixing my code, and then rebuilding and running the container.
Hope that this helps anyone stuck with this issue in future
in pyCharm,
file|
v-->settings|
v-->Version Control|
v-->Git
Here change SSH executable
from Built-in
into Native
then press apply
and close
Environment.GetCommandLineArgs()[0]
A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.
The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.
Ok so i found out the problem :)
ctrl+alt+delete to start task manager, once you get to task manager go to services. find MySQL and right click on it. Then click stop process. That worked for me and i hope it works for you :D
You can also use Guava and do something like this:
// This method returns enum for a given string if it exists, otherwise it returns default enum.
private MyEnum getMyEnum(String enumName) {
// It is better to return default instance of enum instead of null
return hasMyEnum(enumName) ? MyEnum.valueOf(enumName) : MyEnum.DEFAULT;
}
// This method checks that enum for a given string exists.
private boolean hasMyEnum(String enumName) {
return Iterables.any(Arrays.asList(MyEnum.values()), new Predicate<MyEnum>() {
public boolean apply(MyEnum myEnum) {
return myEnum.name().equals(enumName);
}
});
}
In second method I use guava (Google Guava) library which provides very useful Iterables class. Using the Iterables.any() method we can check if a given value exists in a list object. This method needs two parameters: a list and Predicate object. First I used Arrays.asList() method to create a list with all enums. After that I created new Predicate object which is used to check if a given element (enum in our case) satisfies the condition in apply method. If that happens, method Iterables.any() returns true value.
Using CSS you can just set display:none for the element in a CSS file or in a style attribute
#div { display:none; }
<div id="div"></div>
<div style="display:none"></div>
or having the js just after the div might be fast enough too, but not as clean
My issue was the failure to import numpy into my python files. I was receiving the "ModuleNotFoundError: No module named 'numpy'". I ran into the same issue and I was not referencing python3 on the installation of numpy. I inputted the following into my terminal for OSX and my problems were solved:
python3 -m pip install numpy
There is a specific method to do this:
$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');
You can also use:
$objPHPExcel->setActiveSheetIndex(0)->mergeCells('A1:C1');
That should do the trick.
Just in case someone looking for a solution to this for a Windows based system or NAS:
There is a built-in function in Windows that shows you what files on the local computer are open/locked by remote computer (which has the file open through a file share):
There you can even close the file forcefully.
I was having the same error, but i fixed it after reinstalling the HAXM. This problem is caused because of the virtual device not starting properly. If your device keep showing on screen "Android" or the screen is black, it have not started yet, you have to wait more for it to start properly, then it shall run. If it is too slow, maybe you should find a way to accelerate the Android Virtual Device (AVD). The Intel computers have the HAXM (hardware-accelerated-execution-manager).
In my computer was not starting because of the HAXM not working, I fixed it by reinstalling the HAXM, downloading it from the intel website: "https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager"
Then i set the HAXM max memory to 1536MB in the installation, for not having the problem of this other post, that you maybe have and i was having too: "HAXM configuration in android studio"
After all done, it worked fine.
Frankly speaking, your case works fine for me!
I'm using Angular 5.
<script type='text/javascript'>
var base = window.location.href.substring(0, window.location.href.toLowerCase().indexOf('index.aspx'))
document.write('<base href="' + base + '" />');
</script>
You've imported the certificate into the truststore of the JRE provided in the JDK, but you are running the java.exe of the JRE installed directly.
EDIT
For clarity, and to resolve the morass of misunderstanding in the commentary below, you need to import the certificate into the cacerts
file of the JRE you are intending to use, and that will rarely if ever be the one shipping inside the JDK, because clients won't normally have a JDK. Anything in the commentary below that suggests otherwise should be ignored as not expressing my intention here.
A far better solution would be to create your own truststore, starting with a copy of the cacerts
file, and specifically tell Java to use that one via the system property javax.net.ssl.trustStore.
You should make building this part of your build process, so as to keep up to date with changes I the cacerts
file caused by JDK upgrades.
Use a smarty template for your stuff then just set the POST array as a smarty array and open the template. In the template just echo out the array so if it passes:
if(correct){
header("Location: passed.php");
} else {
$smarty->assign("variables", $_POST);
$smarty->display("register_error.php");
exit;
}
I have not tried this yet but I am going to try it as a solution and will let you know what I find. But of course this method assumes that you are using smarty.
If not you can just recreate your form there on the error page and echo info into the form or you could send back non important data in a get from and get it
ex.
register.php?name=mr_jones&address==......
echo $_GET[name];
Use /config.php
.
This one helped me,
res.format({
json:function(){
var responseData = {};
responseData['status'] = 200;
responseData['outputPath'] = outputDirectoryPath;
responseData['sourcePath'] = url;
responseData['message'] = 'Scraping of requested resource initiated.';
responseData['logfile'] = logFileName;
res.json(JSON.stringify(responseData));
}
});
Try a different usb cable. My cable was bad. Charging was ok but did not attach the phone.
There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.
The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.
To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.
Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:
var items = $.map(keys, function(item, i) {
var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
return
'{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
'" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
});
var jsonObj =
'{"code":"' + code + '",'+
'"defaultfile":"' + defaultfile + '",'+
'"filename":"' + currentFile + '",'+
'"lstResDef":[' + items.join(',') + ']}';
On the Mac you can also use ?+K
just like in Terminal.
I run netstat -nao | findstr 5037
in cmd.
As you see there is a process with id 3888. I kill it with taskkill /f /pid 3888
if you have more than one, kill all.
after that run adb with adb start-server
, my adb run sucessfully.
The meaning of CascadeType.ALL
is that the persistence will propagate (cascade) all EntityManager
operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH
) to the relating entities.
It seems in your case to be a bad idea, as removing an Address
would lead to removing the related User
. As a user can have multiple addresses, the other addresses would become orphans. However the inverse case (annotating the User
) would make sense - if an address belongs to a single user only, it is safe to propagate the removal of all addresses belonging to a user if this user is deleted.
BTW: you may want to add a mappedBy="addressOwner"
attribute to your User
to signal to the persistence provider that the join column should be in the ADDRESS table.
You can try this:
-ms-transform: scale(width,height); /* IE 9 */
-webkit-transform: scale(width,height); /* Safari */
transform: scale(width, height);
Example: image "grows" 1.3 times
-ms-transform: scale(1.3,1.3); /* IE 9 */
-webkit-transform: scale(1.3,1.3); /* Safari */
transform: scale(1.3,1.3);
Perhaps using the textDecoder will be sufficient.
Not supported in IE though.
var decoder = new TextDecoder('utf-8'),
decodedMessage;
decodedMessage = decoder.decode(message.data);
In this example, we decode the Russian text "??????, ???!", which means "Hello, world." In our TextDecoder() constructor, we specify the Windows-1251 character encoding, which is appropriate for Cyrillic script.
let win1251decoder = new TextDecoder('windows-1251');
let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
console.log(win1251decoder.decode(bytes)); // ??????, ???!
_x000D_
The interface for the TextDecoder is described here.
Retrieving a byte array from a string is equally simpel:
const decoder = new TextDecoder();
const encoder = new TextEncoder();
const byteArray = encoder.encode('Größe');
// converted it to a byte array
// now we can decode it back to a string if desired
console.log(decoder.decode(byteArray));
_x000D_
If you have it in a different encoding then you must compensate for that upon encoding. The parameter in the constructor for the TextEncoder is any one of the valid encodings listed here.
I had the same problem when i installed xampp on my system. The mysql server looks for /var/run/mysqld/mysqld.sock but the mysql.sock file was in xampp folder so i used
find / -name '*.sock'
to find the mysql.sock file and then used
ln -s <the file location> /var/run/mysqld/mysqld.sock
to get a link for the *.sock file then tried mysql and it ran without error. Hope this could solve yours.
Remember to create the directory if it does not exists.
Below are some important differences in promises & Observables.
Promise
Observable
For better understanding refer to the https://stackblitz.com/edit/observable-vs-promises
Modeling your api on existing 'best practices' might be the way to go. For example, here is how Twitter handles error codes https://developer.twitter.com/en/docs/basics/response-codes
I think you want to extract a column from an array such as an array below
import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
Now if you want to get the third column in the format
D=array[[3],
[7],
[11]]
Then you need to first make the array a matrix
B=np.asmatrix(A)
C=B[:,2]
D=asarray(C)
And now you can do element wise calculations much like you would do in excel.
I stumbled on this question while trying to do the same thing (I think). Here is how I did it:
df['index_col'] = df.index
You can then sort on the new index column, if you like.
Encountered a similar problem after upgrading to Catalina OS. After running mysqld command, I found that there was some issue with the logs file. It could be different for others.
$ mysqld
Issue was
2019-10-16T04:58:59.174474Z 0 [ERROR] Could not open file '/var/log/mysql/error.log' for error logging: No such file or directory
2019-10-16T04:58:59.174508Z 0 [ERROR] Aborting
Resolved it by creating it and applying proper permissions.
sudo mkdir -p /var/log/mysql
sudo touch /var/log/mysql/error.log
sudo chown -R _mysql:mysql /var/log/mysql/
Restart MySQL
brew services restart [email protected]
Issue was resolved.
mysql -uroot -proot
If you're using LESS CSS, I wrote a little mixin to move the dropdown with the connecting arrow:
.dropdown-menu-shift( @num-pixels, @arrow-position: 10px ) { // mixin to shift the dropdown menu
left: @num-pixels;
&:before { left: -@num-pixels + @arrow-position; } // triangle outline
&:after { left: -@num-pixels + @arrow-position + 1px; } // triangle internal
}
Then to move a .dropdown-menu
with an id of dropdown-menu-x
for example, you can do:
#dropdown-menu-x {
.dropdown-menu-shift( -100px );
}
You can use npm i y-websockets-server
and then use the below command
y-websockets-server --port 11000
and here in my case, the port No is 11000.
You can access the index attribute of a df using .index
:
In [277]:
df = pd.DataFrame({'a':np.arange(10), 'b':np.random.randn(10)})
df
Out[277]:
a b
0 0 0.293422
1 1 -1.631018
2 2 0.065344
3 3 -0.417926
4 4 1.925325
5 5 0.167545
6 6 -0.988941
7 7 -0.277446
8 8 1.426912
9 9 -0.114189
In [278]:
df.index
Out[278]:
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')
For those that do know the width, you could do something like
div {
max-width: ???px; //px,%
margin-left:auto;
margin-right:auto;
}
I also agree about not setting text-align:center on the body because it can mess up the rest of your code and you might have to individually set text-align:left on a lot of things either then or in the future.
Inspired by Martijn Pieters' response.
In case you only need to delete the header from the csv
file, you can work more efficiently if you write using the standard Python file I/O library, avoiding writing with the CSV Python library:
with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
next(infile) # skip the headers
outfile.write(infile.read())
The variable item
is a string. An index looks like this:
>>> mystring = 'helloworld'
>>> print mystring[0]
'h'
The above example uses the 0
index of the string to refer to the first character.
Strings can't have string indices (like dictionaries can). So this won't work:
>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers
You can use like this:
removeDepartment(name: string): void {
this.departments = this.departments.filter(item => item != name);
}
json.dumps()
is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None
, the str()
would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps()
would convert None
into null
making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.
export function foo() { console.log('foo') },
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }
In this case you are export all of the functions with names, so you could do
import * as fns from './foo';
to get an object with properties for each function instead of the import you'd use for your first example:
import fns from './foo';
To add or delete elements entirely which would alter the index, by way of extension of zhujy_8833 suggestion of slice() to iterate over a copy, simply count the number of elements you have already deleted or added and alter the index accordingly. For example, to delete elements:
let values = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"];
let count = 0;
values.slice().forEach((value, index) => {
if (value === "A2" || value === "A5") {
values.splice(index - count++, 1);
};
});
console.log(values);
// Expected: [ 'A0', 'A1', 'A3', 'A4', 'A6', 'A7', 'A8' ]
To insert elements before:
if (value === "A0" || value === "A6" || value === "A8") {
values.splice(index - count--, 0, 'newVal');
};
// Expected: ['newVal', A0, 'A1', 'A2', 'A3', 'A4', 'A5', 'newVal', 'A6', 'A7', 'newVal', 'A8' ]
To insert elements after:
if (value === "A0" || value === "A6" || value === "A8") {
values.splice(index - --count, 0, 'newVal');
};
// Expected: ['A0', 'newVal', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'newVal', 'A7', 'A8', 'newVal']
To replace an element:
if (value === "A3" || value === "A4" || value === "A7") {
values.splice(index, 1, 'newVal');
};
// Expected: [ 'A0', 'A1', 'A2', 'newVal', 'newVal', 'A5', 'A6', 'newVal', 'A8' ]
Note: if implementing both 'before' and 'after' inserts, code should handle 'before' inserts first, other way around would not be as expected
Enclose the paths containing spaces with double quotes.
cmd /C "C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*"
I have added complete solution and example using NTree class above, also added "AddChild" method...
public class NTree<T>
{
public T data;
public LinkedList<NTree<T>> children;
public NTree(T data)
{
this.data = data;
children = new LinkedList<NTree<T>>();
}
public void AddChild(T data)
{
var node = new NTree<T>(data) { Parent = this };
children.AddFirst(node);
}
public NTree<T> Parent { get; private set; }
public NTree<T> GetChild(int i)
{
foreach (NTree<T> n in children)
if (--i == 0)
return n;
return null;
}
public void Traverse(NTree<T> node, TreeVisitor<T> visitor, string t, ref NTree<T> r)
{
visitor(node.data, node, t, ref r);
foreach (NTree<T> kid in node.children)
Traverse(kid, visitor, t, ref r);
}
}
public static void DelegateMethod(KeyValuePair<string, string> data, NTree<KeyValuePair<string, string>> node, string t, ref NTree<KeyValuePair<string, string>> r)
{
string a = string.Empty;
if (node.data.Key == t)
{
r = node;
return;
}
}
using
NTree<KeyValuePair<string, string>> ret = null;
tree.Traverse(tree, DelegateMethod, node["categoryId"].InnerText, ref ret);
Like @maerics said, your target machine and browser will determine performance.
But for some real world numbers, on my 2017 enterprise Chromebook, running the operation:
console.time();
Array(x).fill(0).filter(x => x < 6).length
console.timeEnd();
x=5e4
takes 16ms, good enough for 60fpsx=4e6
takes 250ms, which is noticeable but not a big dealx=3e7
takes 1300ms, which is pretty badx=4e7
takes 11000ms and allocates an extra 2.5GB of memorySo around 30 million elements is a hard upper limit, because the javascript VM falls off a cliff at 40 million elements and will probably crash the process.
EDIT: In the code above, I'm actually filling the array with elements and looping over them, simulating the minimum of what an app might want to do with an array. If you just run Array(2**32-1)
you're creating a sparse array that's closer to an empty JavaScript object with a length, like {length: 4294967295}
. If you actually tried to use all those 4 billion elements, you'll definitely your user's javascript process.
Before actually answering your question:
Parameters in a URL (e.g. key=listOfUsers/user1
) are GET
parameters and you shouldn't be using them for POST
requests. A quick explanation of the difference between GET and POST can be found here.
In your case, to make use of REST principles, you should probably have:
http://ip:5000/users
http://ip:5000/users/<user_id>
Then, on each URL, you can define the behaviour of different HTTP methods (GET
, POST
, PUT
, DELETE
). For example, on /users/<user_id>
, you want the following:
GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id>
So, in your example, you want do a POST
to /users/user_1
with the POST data being "John"
. Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.
Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
if request.method == 'GET':
"""return the information for <user_id>"""
.
.
.
if request.method == 'POST':
"""modify/update the information for <user_id>"""
# you can use <user_id>, which is a str but could
# changed to be int or whatever you want, along
# with your lxml knowledge to make the required
# changes
data = request.form # a multidict containing POST data
.
.
.
if request.method == 'DELETE':
"""delete user with ID <user_id>"""
.
.
.
else:
# POST Error 405 Method Not Allowed
.
.
.
There are a lot of other things to consider like the POST
request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.
Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.
Jonas's answer does not change the font size of the axes. Sergeyf's answer does not work when there are multiple subplots.
Here is a modification of their answers that works for me when I have multiple subplots:
set(findall(gcf,'type','axes'),'fontsize',30)
set(findall(gcf,'type','text'),'fontSize',30)
Replace
import { Router, Route, Link, browserHistory } from 'react-router';
With
import { BrowserRouter as Router, Route } from 'react-router-dom';
It will start working. It is because react-router-dom exports BrowserRouter
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
foreach ($arr as $val) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
The call
e.extractAll("th")
for a regular method extractAll()
is indeed equivalent to
Extractor.extractAll(e, "th")
These two calls are treated the same in all regards, including the error messages you get.
If you don't need to pass the instance to a method, you can use a staticmethod
:
@staticmethod
def extractAll(tag):
...
which can be called as e.extractAll("th")
. But I wonder why this is a method on a class at all if you don't need to access any instance.
Since nobody has mentioned this..
If all you want is an array of values, an easier alternative would be to use the .map()
method. Just remember to call .get()
to convert the jQuery object to an array:
var names = $('.parent input:checked').map(function () {
return this.name;
}).get();
console.log(names);
var names = $('.parent input:checked').map(function () {_x000D_
return this.name;_x000D_
}).get();_x000D_
_x000D_
console.log(names);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="parent">_x000D_
<input type="checkbox" name="name1" />_x000D_
<input type="checkbox" name="name2" />_x000D_
<input type="checkbox" name="name3" checked="checked" />_x000D_
<input type="checkbox" name="name4" checked="checked" />_x000D_
<input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
Pure JavaScript:
var elements = document.querySelectorAll('.parent input:checked');
var names = Array.prototype.map.call(elements, function(el, i) {
return el.name;
});
console.log(names);
var elements = document.querySelectorAll('.parent input:checked');_x000D_
var names = Array.prototype.map.call(elements, function(el, i){_x000D_
return el.name;_x000D_
});_x000D_
_x000D_
console.log(names);
_x000D_
<div class="parent">_x000D_
<input type="checkbox" name="name1" />_x000D_
<input type="checkbox" name="name2" />_x000D_
<input type="checkbox" name="name3" checked="checked" />_x000D_
<input type="checkbox" name="name4" checked="checked" />_x000D_
<input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
I get this error when running git stash
. Fixed with:
git config --global user.email {emailaddress}
git config --global user.name {name}
class Second:
def __init__(self, data):
self.data = data
class First:
def SecondClass(self, data):
return Second(data)
FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data
Check if you have the hidden folder ".npm" in your Home directory and delete the old angular-cli folder.
Example in Swift, picturing the foundry's explanation above and the Apple's documentation:
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func dismissViewController1AndPresentViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
vc1.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
self.presentViewController(vc1, animated: true, completion: nil)
}
func dismissViewController1AndPresentViewController2() {
self.dismissViewControllerAnimated(false, completion: { () -> Void in
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.presentViewController(vc2, animated: true, completion: nil)
})
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.dismissViewController1AndPresentViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func popViewController1AndPushViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
self.navigationController?.pushViewController(vc1, animated: true)
}
func popViewController1AndPushViewController2() {
self.navigationController?.popViewControllerAnimated(false)
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.navigationController?.pushViewController(vc2, animated: true)
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.popViewController1AndPushViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
If the path in Ubuntu is "/home/ec2-user/Name of Directory", then do this:
1) Java's build.properties file:
build_path='/home/ec2-user/Name\\ of\\ Directory'
Where ~/
is equal to /home/ec2-user
2) Jenkinsfile:
build_path=buildprops['build_path']
echo "Build path= ${build_path}"
sh "cd ${build_path}"
Matheus de Oliveira created handy functions for JSON CRUD operations in postgresql. They can be imported using the \i directive. Notice the jsonb fork of the functions if jsonb if your data type.
9.3 json https://gist.github.com/matheusoliveira/9488951
9.4 jsonb https://gist.github.com/inindev/2219dff96851928c2282
You can also look into using the Collection Object. This usually works better than an array for custom objects, since it dynamically sizes and has methods for:
Plus its normally easier to loop through a collection too since you can use the for...each structure very easily with a collection.
At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:
let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent
I had a similar problem in a MS-Access query, and I solved it by changing my equivalent fName
to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any Group By
clause at the end.
I was using /Date=20161003 in the folder path while doing an insert overwrite and it was failing. I changed it to /Dt=20161003 and it worked
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Iterator;
public class CountFrequencyOfCharater {
public static void main(String args[]) throws Exception
{
HashSet hs=new HashSet();
String str="hey how are you?";
char arr[]=new char[str.length()];
for(int i=0;i<str.length();i++)
{
arr[i]=str.charAt(i);
}
for(int j=0;j<str.length();j++)
{
int c=0;
for(int k=0;k<str.length();k++)
{
if(arr[j]==arr[k])
c++;
}
hs.add(arr[j]+"="+c+",");
}
Iterator it=hs.iterator();
while(it.hasNext())
{
System.out.print(it.next());
}
}
}
None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:
Edit file phpMyAdmin.conf
sudo nano /etc/httpd/conf.d/phpMyAdmin.conf
And replace this at the top:
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
#Require ip 127.0.0.1
#Require ip ::1
Require all granted
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
</IfModule>
</Directory>
you should just be able to call it by typing in the file name. You may have to call ./a.exe as the current directory is usually not on the path for security reasons.
No, it's not. instanceof
would return false
if its first operand is null
.
When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.
I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).
I've found three workarounds that don't require copying the formatting from the source row:
Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)
Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:
Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).
Nobody explained so far why the code in the question doesn't work. My guess is that the code was placed in the constructor of the Window. But at this time it's too early to set the focus. It has to be done once the Window is ready for interaction. The best place for the code is the Loaded event:
public KonsoleWindow() {
public TestWindow() {
InitializeComponent();
Loaded += TestWindow_Loaded;
}
private void TestWindow_Loaded(object sender, RoutedEventArgs e) {
txtCompanyID.Focus();
}
}
You can have an iframe inside the modal markup and give the src attribute of it as the link to your pdf. On click of the link you can show this modal markup.
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
DO NOT USE THIS ANSWER. I HAVE ONLY LEFT IT FOR HISTORICAL PURPOSES. SEE THE COMMENTS BELOW.
There is a simple trick if it is a BOOL parameter.
Pass nil for NO and self for YES. nil is cast to the BOOL value of NO. self is cast to the BOOL value of YES.
This approach breaks down if it is anything other than a BOOL parameter.
Assuming self is a UIView.
//nil will be cast to NO when the selector is performed
[self performSelector:@selector(setHidden:) withObject:nil afterDelay:5.0];
//self will be cast to YES when the selector is performed
[self performSelector:@selector(setHidden:) withObject:self afterDelay:10.0];
You can get the single value for the attribute with below code:
$pa_koostis_value = get_post_meta($product->id, 'pa_koostis', true);
My solution, as answered here, is to use:
var json = require('./data.json'); //with path
The file is loaded only once, further requests use cache.
edit To avoid caching, here's the helper function from this blogpost given in the comments, using the fs
module:
var readJson = (path, cb) => {
fs.readFile(require.resolve(path), (err, data) => {
if (err)
cb(err)
else
cb(null, JSON.parse(data))
})
}
For me just removed the OLE DB source from SSIS and added again. Worked!
Make sure you have the URL correct for whatever you are downloading. First of all, URLs with characters like ?
and such cannot be parsed and resolved. This will confuse the cmd line and accept any characters that aren't resolved into the source URL name as the file name you are downloading into.
For example:
wget "sourceforge.net/projects/ebosse/files/latest/download?source=typ_redirect"
will download into a file named, ?source=typ_redirect
.
As you can see, knowing a thing or two about URLs helps to understand wget
.
I am booting from a hirens disk and only had Linux 2.6.1 as a resource (import os is unavailable). The correct syntax that solved my problem downloading an ISO onto the physical hard drive was:
wget "(source url)" -O (directory where HD was mounted)/isofile.iso"
One could figure the correct URL by finding at what point wget
downloads into a file named index.html
(the default file), and has the correct size/other attributes of the file you need shown by the following command:
wget "(source url)"
Once that URL and source file is correct and it is downloading into index.html
, you can stop the download (ctrl + z) and change the output file by using:
-O "<specified download directory>/filename.extension"
after the source url.
In my case this results in downloading an ISO and storing it as a binary file under isofile.iso
, which hopefully mounts.
In my case I followed this. Summary, in gradle app level: change this :
variant.outputs.all { output ->
variant.assemble.doLast {
....
}
}
to
variant.outputs.all { output ->
variant.getAssembleProvider().configure() {
it.doLast {
....
}
}
Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.
If the purpose of the CSS class on the <form/>
element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/>
element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.
public void excelRead(string sheetName)
{
Excel.Application appExl = new Excel.Application();
Excel.Workbook workbook = null;
try
{
string methodName = "";
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
//Opening Excel file(myData.xlsx)
appExl = new Excel.Application();
workbook = appExl.Workbooks.Open(sheetName, Missing.Value, ReadOnly: false);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
ShtRange = NwSheet.UsedRange; //gives the used cells in sheet
int rCnt1 = 0;
int cCnt1 = 0;
for (rCnt1 = 1; rCnt1 <= ShtRange.Rows.Count; rCnt1++)
{
for (cCnt1 = 1; cCnt1 <= ShtRange.Columns.Count; cCnt1++)
{
if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "Y")
{
methodName = NwSheet.Cells[rCnt1, cCnt1 - 2].Value2;
Type metdType = this.GetType();
MethodInfo mthInfo = metdType.GetMethod(methodName);
if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_AddNum" || Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_SubNum")
{
StaticVariable.intParam1 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 3].Value2);
StaticVariable.intParam2 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 4].Value2);
object[] mParam1 = new object[] { StaticVariable.intParam1, StaticVariable.intParam2 };
object result = mthInfo.Invoke(this, mParam1);
StaticVariable.intOutParam1 = Convert.ToInt32(result);
NwSheet.Cells[rCnt1, cCnt1 + 5].Value2 = Convert.ToString(StaticVariable.intOutParam1) != "" ? Convert.ToString(StaticVariable.intOutParam1) : String.Empty;
}
else
{
object[] mParam = new object[] { };
mthInfo.Invoke(this, mParam);
NwSheet.Cells[rCnt1, cCnt1 + 5].Value2 = StaticVariable.outParam1 != "" ? StaticVariable.outParam1 : String.Empty;
NwSheet.Cells[rCnt1, cCnt1 + 6].Value2 = StaticVariable.outParam2 != "" ? StaticVariable.outParam2 : String.Empty;
}
NwSheet.Cells[rCnt1, cCnt1 + 1].Value2 = StaticVariable.resultOut;
NwSheet.Cells[rCnt1, cCnt1 + 2].Value2 = StaticVariable.resultDescription;
}
else if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "N")
{
MessageBox.Show("Result is No");
}
else if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "EOF")
{
MessageBox.Show("End of File");
}
}
}
workbook.Save();
workbook.Close(true, Missing.Value, Missing.Value);
appExl.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ShtRange);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(NwSheet);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(appExl);
}
catch (Exception)
{
workbook.Close(true, Missing.Value, Missing.Value);
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
System.Runtime.InteropServices.Marshal.CleanupUnusedObjectsInCurrentContext();
}
}
//code for reading excel data in datatable
public void testExcel(string sheetName)
{
try
{
MessageBox.Show(sheetName);
foreach(Process p in Process.GetProcessesByName("EXCEL"))
{
p.Kill();
}
//string fileName = "E:\\inputSheet";
Excel.Application oXL;
Workbook oWB;
Worksheet oSheet;
Range oRng;
// creat a Application object
oXL = new Excel.Application();
// get WorkBook object
oWB = oXL.Workbooks.Open(sheetName);
// get WorkSheet object
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Sheets[1];
System.Data.DataTable dt = new System.Data.DataTable();
//DataSet ds = new DataSet();
//ds.Tables.Add(dt);
DataRow dr;
StringBuilder sb = new StringBuilder();
int jValue = oSheet.UsedRange.Cells.Columns.Count;
int iValue = oSheet.UsedRange.Cells.Rows.Count;
// get data columns
for (int j = 1; j <= jValue; j++)
{
oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, j];
string strValue = oRng.Text.ToString();
dt.Columns.Add(strValue, System.Type.GetType("System.String"));
}
//string colString = sb.ToString().Trim();
//string[] colArray = colString.Split(':');
// get data in cell
for (int i = 2; i <= iValue; i++)
{
dr = dt.NewRow();
for (int j = 1; j <= jValue; j++)
{
oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[i, j];
string strValue = oRng.Text.ToString();
dr[j - 1] = strValue;
}
dt.Rows.Add(dr);
}
if(StaticVariable.dtExcel != null)
{
StaticVariable.dtExcel.Clear();
StaticVariable.dtExcel = dt.Copy();
}
else
StaticVariable.dtExcel = dt.Copy();
oWB.Close(true, Missing.Value, Missing.Value);
oXL.Quit();
MessageBox.Show(sheetName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
//code for class initialize
public static void startTesting(TestContext context)
{
Playback.Initialize();
ReadExcel myClassObj = new ReadExcel();
string sheetName="";
StreamReader sr = new StreamReader(@"E:\SaveSheetName.txt");
sheetName = sr.ReadLine();
sr.Close();
myClassObj.excelRead(sheetName);
myClassObj.testExcel(sheetName);
}
//code for test initalize
public void runValidatonTest()
{
DataTable dtFinal = StaticVariable.dtExcel.Copy();
for (int i = 0; i < dtFinal.Rows.Count; i++)
{
if (TestContext.TestName == dtFinal.Rows[i][2].ToString() && dtFinal.Rows[i][3].ToString() == "Y" && dtFinal.Rows[i][4].ToString() == "TRUE")
{
MessageBox.Show(TestContext.TestName);
MessageBox.Show(dtFinal.Rows[i][2].ToString());
StaticVariable.runValidateResult = "true";
break;
}
}
//StaticVariable.dtExcel = dtFinal.Copy();
}
You must to upgrade the m2e connector. It's a known bug, but there is a solution:
Into Eclipse click "Help" > "Install new Software..."
Appears a window. In the "Install" window:
2a. Into the input box "Work with", enter next site location and press Enter https://download.eclipse.org/m2e-wtp/releases/1.4/
2b. Appears a lot of information into "Name" input Box. Select all the items
2c. Click "Next" Button.
Finish the installation and restart Eclipse.
A Build Lifecycle is Made Up of Phases
Each of these build lifecycles is defined by a different list of build phases, wherein a build phase represents a stage in the lifecycle.
For example, the default lifecycle comprises of the following phases (for a complete list of the lifecycle phases, refer to the Lifecycle Reference):
These lifecycle phases (plus the other lifecycle phases not shown here) are executed sequentially to complete the default lifecycle. Given the lifecycle phases above, this means that when the default lifecycle is used, Maven will first validate the project, then will try to compile the sources, run those against the tests, package the binaries (e.g. jar), run integration tests against that package, verify the integration tests, install the verified package to the local repository, then deploy the installed package to a remote repository.
Source: https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html
Pretty much everybody is using getopt
Here is the example code for the doc :
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError:
# print help information and exit:
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-o", "--output"):
output = a
So in a word, here is how it works.
You've got two types of options. Those who are receiving arguments, and those who are just like switches.
sys.argv
is pretty much your char** argv
in C. Like in C you skip the first element which is the name of your program and parse only the arguments : sys.argv[1:]
Getopt.getopt
will parse it according to the rule you give in argument.
"ho:v"
here describes the short arguments : -ONELETTER
. The :
means that -o
accepts one argument.
Finally ["help", "output="]
describes long arguments ( --MORETHANONELETTER
).
The =
after output once again means that output accepts one arguments.
The result is a list of couple (option,argument)
If an option doesn't accept any argument (like --help
here) the arg
part is an empty string.
You then usually want to loop on this list and test the option name as in the example.
I hope this helped you.
System.Net.WebException: The remote server returned an error: (411) Length Required.
This is a pretty common issue that comes up when trying to make call a REST based API method through POST. Luckily, there is a simple fix for this one.
This is the code I was using to call the Windows Azure Management API. This particular API call requires the request method to be set as POST, however there is no information that needs to be sent to the server.
var request = (HttpWebRequest) HttpWebRequest.Create(requestUri);
request.Headers.Add("x-ms-version", "2012-08-01"); request.Method =
"POST"; request.ContentType = "application/xml";
To fix this error, add an explicit content length to your request before making the API call.
request.ContentLength = 0;
>>> x = (u'2',)
>>> x += u"random string"
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", ) # concatenate a one-tuple instead
>>> x
(u'2', u'random string')
Just use look-arounds to solve this:
(?<=^|,)garp(?=$|,)
The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.
Regular implementation (no yield - will do everything in memory):
def getPermutations(array):
if len(array) == 1:
return [array]
permutations = []
for i in range(len(array)):
# get all perm's of subarray w/o current item
perms = getPermutations(array[:i] + array[i+1:])
for p in perms:
permutations.append([array[i], *p])
return permutations
Yield implementation:
def getPermutations(array):
if len(array) == 1:
yield array
else:
for i in range(len(array)):
perms = getPermutations(array[:i] + array[i+1:])
for p in perms:
yield [array[i], *p]
The basic idea is to go over all the elements in the array for the 1st position, and then in 2nd position go over all the rest of the elements without the chosen element for the 1st, etc. You can do this with recursion, where the stop criteria is getting to an array of 1 element - in which case you return that array.
You can change the Font Awesome's icon color with the bootstrap class
use
text-color
example
text-white
Use $dec = $null
From the documentation:
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.
PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.
You can manage to have a pure CSS implementation with max-height
#main-image{
max-height: 0;
overflow: hidden;
background: red;
-prefix-animation: slide 1s ease 3.5s forwards;
}
@keyframes slide {
from {max-height: 0;}
to {max-height: 500px;}
}
You might have to also set padding
, margin
and border
to 0, or simply padding-top
, padding-bottom
, margin-top
and margin-bottom
.
I updated the demo of Duopixel here : http://jsfiddle.net/qD5XX/231/
You are printing the wrong value. Instead if the string you print the scanners object. Try this
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
In my case, /storage/emulated/0/ corresponds to my device's root path. For example, when i take a photo with my phone's default camera application, the images are saved automatically /store/emulated/0/DCIM/Camera/mypicname.jpeg
For example, suppose that you want to store your pictures in /Pictures directory, namely in Pictures directory which exist in root directory. So you use the below code.
File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES );
If you want to save the images in DCIM or Downloads directory, give the below arguments to the Environment.getExternalStoragePublicDirectory() method shown above.
Environment.DIRECTORY_DCIM
Environment.DIRECTORY_Downloads
Then specify your image name :
String imageFileName = "JPEG_" + timeStamp + "_";
Then create the file object as shown below. You specify the suffix as the 2nd argument.
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
You can use MediaQuery for parent's dimension or FractionallySizedBox as containers.
You can use as_json
method. It'll convert your object into hash.
But, that hash will come as a value to the name of that object as a key. In your case,
{'gift' => {'name' => 'book', 'price' => 15.95 }}
If you need a hash that's stored in the object use as_json(root: false)
. I think by default root will be false. For more info refer official ruby guide
http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json
You can always use a hidden div and use javascript to "popup" the div and have buttons that are like yes and or no. Pretty easy stuff to do.
Git GUI has a PUSH button - pardon the pun, and the dialog box it opens has a checkbox for tags.
I pushed a branch from the command line, without tags, and then tried again pushing the branch using the --follow-tags
option descibed above. The option is described as following annotated tags. My tags were simple tags.
I'd fixed something, tagged the commit with the fix in, (so colleagues can cherry pick the fix,) then changed the software version number and tagged the release I created (so colleagues can clone that release).
Git returned saying everything was up-to-date. It did not send the tags! Perhaps because the tags weren't annotated. Perhaps because there was nothing new on the branch.
When I did a similar push with Git GUI, the tags were sent.
For the time being, I am going to be pushing my changes to my remotes with Git GUI and not with the command line and --follow-tags
.
We use this on our website
Its a very customizable to display PDF's directly in your browser. It basically hosts the PDF in a flash object if you are not opposed to that sort of thing.
Here is a sample from our corporate website.
Traditional relational databases were designed as client/server database systems. They can be scaled horizontally but the process to do so tends to be complex and error prone. NewSQL databases like NuoDB are memory-centric distributed database systems designed to scale out horizontally while maintaining the SQL/ACID properties of traditional RDBMS.
For more information on NuoDB, read their technical white paper.
I would generally prefer something a bit simpler, like activate
/deactivate
sub-resource (linked by a Link
header with rel=service
).
POST /groups/api/v1/groups/{group id}/activate
or
POST /groups/api/v1/groups/{group id}/deactivate
For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.
according to VMware's knowledge base, the actual solution depends on the Linux distro and release, in RHEL 5.3 I usually edit /etc/grub.conf and append this parameters to the kernel entry: divider=10 clocksource=acpi_pm
Then enable NTP, disable VMware time synchronization from vmware-toolbox and finally reboot the VM
A complete table with guidelines for each Linux distro can be found here:
TIMEKEEPING BEST PRACTICES FOR LINUX GUESTS http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1006427
Update 2:
Xcode 9 appears to have a "feature" where it will ignore the file's current line endings, and instead just use your default line-ending setting when inserting lines into a file, resulting in files with mixed line endings.
I'm pretty sure this bug didn't exist in Xcode 7; not sure about Xcode 8. The good news is that it appears to be fixed in Xcode 10.
For the time it existed, this bug caused a small amount of hilarity in the codebase I refer to in the question (which to this day uses autocrlf=false
), and led to many "EOL" commit messages and eventually to my writing a git pre-commit
hook to check for/prevent introducing mixed line endings.
Update:
Note: As noted by VonC, starting from Git 2.8, merge markers will not introduce Unix-style line-endings to a Windows-style file.
Original:
One little hiccup that I've noticed with this setup is that when there are merge conflicts, the lines git adds to mark up the differences do not have Windows line-endings, even when the rest of the file does, and you can end up with a file with mixed line endings, e.g.:
// Some code<CR><LF>
<<<<<<< Updated upstream<LF>
// Change A<CR><LF>
=======<LF>
// Change B<CR><LF>
>>>>>>> Stashed changes<LF>
// More code<CR><LF>
This doesn't cause us any problems (I imagine any tool that can handle both types of line-endings will also deal sensible with mixed line-endings--certainly all the ones we use do), but it's something to be aware of.
The other thing* we've found, is that when using git diff
to view changes to a file that has Windows line-endings, lines that have been added display their carriage returns, thus:
// Not changed
+ // New line added in^M
+^M
// Not changed
// Not changed
* It doesn't really merit the term: "issue".
Here is another approach using jQuery,
function uniqueArray(array){
if ($.isArray(array)){
var dupes = {}; var len, i;
for (i=0,len=array.length;i<len;i++){
var test = array[i].toString();
if (dupes[test]) { array.splice(i,1); len--; i--; } else { dupes[test] = true; }
}
}
else {
if (window.console) console.log('Not passing an array to uniqueArray, returning whatever you sent it - not filtered!');
return(array);
}
return(array);
}
Author: William Skidmore
Using @Marc Gravell 's answer, I found a way to use the following method:
source.TakeWhile(x => x != value).Count();
in order to get -1 when the item cannot be found:
internal static class Utils
{
public static int IndexOf<T>(this IEnumerable<T> enumerable, T item) => enumerable.IndexOf(item, EqualityComparer<T>.Default);
public static int IndexOf<T>(this IEnumerable<T> enumerable, T item, EqualityComparer<T> comparer)
{
int index = enumerable.TakeWhile(x => comparer.Equals(x, item)).Count();
return index == enumerable.Count() ? -1 : index;
}
}
I guess this way could be both the fastest and the simpler. However, I've not tested performances yet.
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
The required parameters in an Ajax error
function are jqXHR, exception
and you can use it like below:
$.ajax({
url: 'some_unknown_page.html',
success: function (response) {
$('#post').html(response.responseText);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
},
});
jqXHR:
Its actually an error object which is looks like this
You can also view this in your own browser console, by using console.log
inside the error
function like:
error: function (jqXHR, exception) {
console.log(jqXHR);
// Your error handling logic here..
}
We are using the status
property from this object to get the error code, like if we get status = 404 this means that requested page could not be found. It doesn't exists at all. Based on that status code we can redirect users to login page or whatever our business logic requires.
exception:
This is string variable which shows the exception type. So, if we are getting 404 error, exception
text would be simply 'error'. Similarly, we might get 'timeout', 'abort' as other exception texts.
Deprecation Notice: The
jqXHR.success()
,jqXHR.error()
, andjqXHR.complete()
callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, usejqXHR.done()
,jqXHR.fail()
, andjqXHR.always()
instead.
So, in case you are using jQuery 1.8 or above we will need to update the success and error function logic like:-
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax("some_unknown_page.html")
.done(function (response) {
// success logic here
$('#post').html(response.responseText);
})
.fail(function (jqXHR, exception) {
// Our error logic here
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
})
.always(function () {
alert("complete");
});
Hope it helps!
//add this to your css
.myClass{
margin 0 auto;
}
// add the class to the span tag( could add it to the div and not using a span
// at all
<div class="row">
<div class="col-xs-1 center-block">
<span class="myClass">aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</div>
</div>
Darrel is of course right on with his response. One thing to add is that the reason why attempting to bind to a body containing a single token like "hello".
is that it isn’t quite URL form encoded data. By adding “=” in front like this:
=hello
it becomes a URL form encoding of a single key value pair with an empty name and value of “hello”.
However, a better solution is to use application/json when uploading a string:
POST /api/sample HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: host:8080
Content-Length: 7
"Hello"
Using HttpClient you can do it as follows:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync(_baseAddress + "api/json", "Hello");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
Henrik
You can run the pipenv
command with the --rm
option as in:
pipenv --rm
This will remove the virtualenv created for you under ~/.virtualenvs
See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm
HTML:
<div class="form-group">
<label for="pt_date" class="col-2 col-form-label">Date</label>
<input class="form-control" type="date" value=<?php echo date("Y-m-d") ;?> id="pt_date" name="pt_date">
</div>
SQL
$pt_date = $_POST['pt_date'];
$sql = "INSERT INTO `table` ( `pt_date`) VALUES ( '$pt_date')";
I got a different idea:
First:
pip install python-dotenv
Install the python-dotenv
module, which will read local preference for your project environment.
Second:
Add .flaskenv
file in your project directory. Add following code:
FLASK_ENV=development
It's done!
With this config for your Flask project, when you run flask run
and you will see this output in your terminal:
And when you edit your file, just save the change. You will see auto-reload is there for you:
With more explanation:
Of course you can manually hit export FLASK_ENV=development
every time you need. But using different configuration file to handle the actual working environment seems like a better solution, so I strongly recommend this method I use.
As an addition, if have Sublime Text installed in your development computer, you can drag the file to your opened Sublime Text window, right click the filename -> rename and enter whatever name even without any extension. This worked for me.
=SUMPRODUCT((A1:A5="FRANCE")*B1:D5)
Perhaps you should not store data that way. It is a bad practice to ever store a comma delimited list in a field. IT is very inefficient for querying. This should be a related table.
How about using grep -E
?
echo "This is 02G05 a test string 20-Jul-2012" | grep -Eo '[0-9]+G[0-9]+'
I had the same problem, I solved it by removing venv directory and recreating it!
deactivate (if venv is activated first deactivate it)
rm -rf venv
virtualenv -p python3 venv
. ENV/bin/activate
pip3 install -r requirements.txt
Now everything works like a charm.
( # Start of group
(?=.*\d) # must contain at least one digit
(?=.*[A-Z]) # must contain at least one uppercase character
(?=.*\W) # must contain at least one special symbol
. # match anything with previous condition checking
{8,8} # length is exactly 8 characters
) # End of group
In one line:
((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,8})
You need to match entire input string. So, you can enclose the regex between ^
and $
to prevent accidentally assuming partial matches as matching entire input:
^((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,8})$
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
we can use java 8 to do a null-friendly comparasion between object. supposed i hava a Boy class with 2 fields: String name and Integer age and i want to first compare names and then ages if both are equal.
static void test2() {
List<Boy> list = new ArrayList<>();
list.add(new Boy("Peter", null));
list.add(new Boy("Tom", 24));
list.add(new Boy("Peter", 20));
list.add(new Boy("Peter", 23));
list.add(new Boy("Peter", 18));
list.add(new Boy(null, 19));
list.add(new Boy(null, 12));
list.add(new Boy(null, 24));
list.add(new Boy("Peter", null));
list.add(new Boy(null, 21));
list.add(new Boy("John", 30));
List<Boy> list2 = list.stream()
.sorted(comparing(Boy::getName,
nullsLast(naturalOrder()))
.thenComparing(Boy::getAge,
nullsLast(naturalOrder())))
.collect(toList());
list2.stream().forEach(System.out::println);
}
private static class Boy {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boy(String name, Integer age) {
this.name = name;
this.age = age;
}
public String toString() {
return "name: " + name + " age: " + age;
}
}
and the result:
name: John age: 30
name: Peter age: 18
name: Peter age: 20
name: Peter age: 23
name: Peter age: null
name: Peter age: null
name: Tom age: 24
name: null age: 12
name: null age: 19
name: null age: 21
name: null age: 24
If you just want to check type of passed variable, you could probably use:
var a = 2;
if (a is int)
{
//is integer
}
//or:
if (a.GetType() == typeof(int))
{
//is integer
}
You can use curlrequest to easily set what time of request you want to do... you can even set headers in the options to "fake" a browser call.
You dont need to define option tags, you can do this using the ngOptions directive: https://docs.angularjs.org/api/ng/directive/ngOptions
<select class="form-control" ng-change="unitChanged()" ng-model="data.unit" ng-options="unit.id as unit.label for unit in units"></select>
Android Supports SSL implementation by default except for Android N (API level 24) and below Android 5.1 (API level 22)
I was getting the error when making the API call below API level 22 devices after implementing SSL at the server side; that was while creating OkHttpClient client object, and fixed by adding connectionSpecs() method OkHttpClient.Builder class.
the error received was
response failure: javax.net.ssl.SSLException: SSL handshake aborted: ssl=0xb8882c00: I/O error during system call, Connection reset by peer
so I fixed this by added the check like
if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
// Do something for below api level 22
List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
if (specsList != null) {
okb.connectionSpecs(specsList);
}
}
Also for the Android N (API level 24); I was getting the error while making the HTTP call like
HTTP FAILED: javax.net.ssl.SSLHandshakeException: Handshake failed
and this is fixed by adding the check for Android 7 particularly, like
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
// Do something for naugat ; 7
okb.connectionSpecs(Collections.singletonList(getSpec()));
}
So my final OkHttpClient object will be like:
OkHttpClient client
HttpLoggingInterceptor httpLoggingInterceptor2 = new
HttpLoggingInterceptor();
httpLoggingInterceptor2.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder okb = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor2)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request request2 = request.newBuilder().addHeader(AUTH_KEYWORD, AUTH_TYPE_JW + " " + password).build();
return chain.proceed(request2);
}
}).connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS);
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
// Do something for naugat ; 7
okb.connectionSpecs(Collections.singletonList(getSpec()));
}
if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
if (specsList != null) {
okb.connectionSpecs(specsList);
}
}
//init client
client = okb.build();
getSpecsBelowLollipopMR1 function be like,
private List<ConnectionSpec> getSpecsBelowLollipopMR1(OkHttpClient.Builder okb) {
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, null);
okb.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));
ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build();
List<ConnectionSpec> specs = new ArrayList<>();
specs.add(cs);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
return specs;
} catch (Exception exc) {
Timber.e("OkHttpTLSCompat Error while setting TLS 1.2"+ exc);
return null;
}
}
The Tls12SocketFactory class will be found in below link (comment by gotev):
https://github.com/square/okhttp/issues/2372
For more support adding some links below this will help you in detail,
https://developer.android.com/training/articles/security-ssl
SOLUTIONS
g++
. So install g++
first and then recreate your project. This worked for me.CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++
Note the path to g++
depends on OS. I have used my fedora path obtained using which g++
The HTTP spec and Firebug were very useful for me when I had to do it for my homework.
Good luck with yours. :)
I'd suggest that the -i
means it does match "ABC", but the difference is in the output. -i
doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o
says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.
The output of echo "ABC" | grep -i abc
is ABC
, the -o
shows output matching "abc" so nothing shows:
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC
How about treat the external script as a Java class? Based on this article: https://www.jmdawson.net/blog/2014/08/18/using-functions-from-one-groovy-script-in-another/
getThing.groovy The external script
def getThingList() {
return ["thing","thin2","thing3"]
}
printThing.groovy The main script
thing = new getThing() // new the class which represents the external script
println thing.getThingList()
Result
$ groovy printThing.groovy
[thing, thin2, thing3]
As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below
e.g.
Exec N'Select bla..'
the N defines string literal is unicode.
Call this method to change app locale:
public void settingLocale(Context context, String language) {
Locale locale;
Configuration config = new Configuration();
if(language.equals(LANGUAGE_ENGLISH)) {
locale = new Locale("en");
Locale.setDefault(locale);
config.locale = locale;
}else if(language.equals(LANGUAGE_ARABIC)){
locale = new Locale("hi");
Locale.setDefault(locale);
config.locale = locale;
}
context.getResources().updateConfiguration(config, null);
// Here again set the text on view to reflect locale change
// and it will pick resource from new locale
tv1.setText(R.string.one); //tv1 is textview in my activity
}
Note: Put your strings in value and values- folder.
You need to
#include <string>
<iostream>
declares cout
, cin
, not string
.
Update for Django 1.10+:
is_authenticated
is now an attribute in Django 1.10.
The method was removed in Django 2.0.
For Django 1.9 and older:
is_authenticated
is a function. You should call it like
if request.user.is_authenticated():
# do something if the user is authenticated
As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:
{% if user.is_authenticated %}
However, in Python code, it is indeed a method in the User
class.
Just change the DropDownStyle
to DropDownList
. Or if you want it completely read only you can set Enabled = false
, or if you don't like the look of that I sometimes have two controls, one readonly textbox and one combobox and then hide the combo and show the textbox if it should be completely readonly and vice versa.
There was a bug in iOS 6, that causes line height to be ignored when font is set. See answer to NSParagraphStyle line spacing ignored and longer bug analysis at Radar: UITextView Ignores Minimum/Maximum Line Height in Attributed String.
Use two single-quotes
SQL> SELECT 'D''COSTA' name FROM DUAL;
NAME
-------
D'COSTA
Alternatively, use the new (10g+) quoting method:
SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;
NAME
-------
D'COSTA
I would just do
var list = new List<string> { "hello" };
select distinct 'GRANT '||privilege||' ON '||OWNER||'.'||TABLE_NAME||' TO '||RP.GRANTEE
from DBA_ROLE_PRIVS RP join ROLE_TAB_PRIVS RTP
on (RP.GRANTED_ROLE = RTP.role)
where (OWNER in ('YOUR USER') --Change User Name
OR RP.GRANTEE in ('YOUR USER')) --Change User Name
and RP.GRANTEE not in ('SYS', 'SYSTEM')
;
There is an Android api that allows the user to select their email address without the need for a permission. Take a look at: https://developers.google.com/identity/smartlock-passwords/android/retrieve-hints
HintRequest hintRequest = new HintRequest.Builder()
.setHintPickerConfig(new CredentialPickerConfig.Builder()
.setShowCancelButton(true)
.build())
.setEmailAddressIdentifierSupported(true)
.setAccountTypes(IdentityProviders.GOOGLE)
.build();
PendingIntent intent = mCredentialsClient.getHintPickerIntent(hintRequest);
try {
startIntentSenderForResult(intent.getIntentSender(), RC_HINT, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Could not start hint picker Intent", e);
}
This will show a picker where the user can select an emailaddress. The result will be delivered in onActivityResult()
Use crontab to add job
crontab -e
And job should be in this format:
00 19 * * 1,3,5 /home/user/somejob.sh
The lightweight MooTools framework has one: http://demos.mootools.net/Slider
end(preg_split("#(\\\\|\\/)#", Class_Name::class))
Class_Name::class
: return the class with the namespace. So after you only need to create an array, then get the last value of the array.
For Debian. Required packages are: m4 automake pkg-config libtool
zoom: 145%;
-moz-transform: scale(1.45);
use this to be on the safer side
Dim celltxt As String
Range("C6").Select
Selection.End(xlToRight).Select
celltxt = Selection.Text
If InStr(1, celltext, "TOTAL") > 0 Then
Range("C7").Select
Selection.End(xlToRight).Select
Selection.Value = "-"
End If
You declared "celltxt" and used "celltext" in the instr.
As of 20/03/2019 -> There is a new version of Crystal report for Visual Studio. The version is 13.0.24.
The provided version in the accepted answer is 13.0.21.
The newer version worked for me without having to do any workaround.
I know the question is already closed but I've found it searching for same TypeScriptException, maybe some one else hit this question searching for this problem.
The problem lays in missing TypeScript typing:
var coordinates = outerElement[0].getBBox();
Throws The property 'getBBox' does not exist on value of type 'HTMLElement'.
var outerHtmlElement: any = outerElement[0];
var coordinates = outerHtmlElement.getBBox();
Since TypeScript 1.6, the prefered casting operator is as
, so those lines can be squashed into:
let coordinates = (outerElement[0] as any).getBBox();
Of course if you'd like to do it right, which is an overkill sometimes, you can:
HTMLElement
HTMLElement
http://asktom.oracle.com/tkyte/Misc/DateDiff.html - link dead as of 2012-01-30
Looks like this is the resource:
http://asktom.oracle.com/pls/asktom/ASKTOM.download_file?p_file=6551242712657900129
The other answers only show the changed files.
git log -p DIR
is very useful, if you need the full diff of all changed files in a specific subdirectory.
Example: Show all detailed changes in a specific version range
git log -p 8a5fb..HEAD -- A B
commit 62ad8c5d
Author: Scott Tiger
Date: Mon Nov 27 14:25:29 2017 +0100
My comment
...
@@ -216,6 +216,10 @@ public class MyClass {
+ Added
- Deleted
I had to deal with that problem recently and came up with a solution, which works just fine for me. However, I've tried @Ori Drori solution above and unfortunately it didn't work just right (had some delays + I don't like the usage of setTimeout
function there).
index.html
file
Inside head
tag - styles for the indicator:
<style media="screen" type="text/css">
.loading {
-webkit-animation: sk-scaleout 1.0s infinite ease-in-out;
animation: sk-scaleout 1.0s infinite ease-in-out;
background-color: black;
border-radius: 100%;
height: 6em;
width: 6em;
}
.container {
align-items: center;
background-color: white;
display: flex;
height: 100vh;
justify-content: center;
width: 100vw;
}
@keyframes sk-scaleout {
0% {
-webkit-transform: scale(0);
transform: scale(0);
}
100% {
-webkit-transform: scale(1.0);
opacity: 0;
transform: scale(1.0);
}
}
</style>
Now the body
tag:
<div id="spinner" class="container">
<div class="loading"></div>
</div>
<div id="app"></div>
And then comes a very simple logic, inside app.js
file (in the render function):
const spinner = document.getElementById('spinner');
if (spinner && !spinner.hasAttribute('hidden')) {
spinner.setAttribute('hidden', 'true');
}
How does it work?
When the first component (in my app it's app.js
aswell in most cases) mounts correctly, the spinner
is being hidden with applying hidden
attribute to it.
What's more important to add -
!spinner.hasAttribute('hidden')
condition prevents to add hidden
attribute to the spinner with every component mount, so actually it will be added only one time, when whole app loads.
use range, or DateDiff function
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
or
select * from test
where datediff(day, date, '03/19/2014') = 0
Other options are:
If you have control over the database schema, and you don't need the time data, take it out.
or, if you must keep it, add a computed column attribute that has the time portion of the date value stripped off...
Alter table Test
Add DateOnly As
DateAdd(day, datediff(day, 0, date), 0)
or, in more recent versions of SQL Server...
Alter table Test
Add DateOnly As
Cast(DateAdd(day, datediff(day, 0, date), 0) as Date)
then, you can write your query as simply:
select * from test
where DateOnly = '03/19/2014'
Here is some code I wrote to help us identify and correct untrusted CONSTRAINTs in a DATABASE. It generates the code to fix each issue.
;WITH Untrusted (ConstraintType, ConstraintName, ConstraintTable, ParentTable, IsDisabled, IsNotForReplication, IsNotTrusted, RowIndex) AS
(
SELECT
'Untrusted FOREIGN KEY' AS FKType
, fk.name AS FKName
, OBJECT_NAME( fk.parent_object_id) AS FKTableName
, OBJECT_NAME( fk.referenced_object_id) AS PKTableName
, fk.is_disabled
, fk.is_not_for_replication
, fk.is_not_trusted
, ROW_NUMBER() OVER (ORDER BY OBJECT_NAME( fk.parent_object_id), OBJECT_NAME( fk.referenced_object_id), fk.name) AS RowIndex
FROM
sys.foreign_keys fk
WHERE
is_ms_shipped = 0
AND fk.is_not_trusted = 1
UNION ALL
SELECT
'Untrusted CHECK' AS KType
, cc.name AS CKName
, OBJECT_NAME( cc.parent_object_id) AS CKTableName
, NULL AS ParentTable
, cc.is_disabled
, cc.is_not_for_replication
, cc.is_not_trusted
, ROW_NUMBER() OVER (ORDER BY OBJECT_NAME( cc.parent_object_id), cc.name) AS RowIndex
FROM
sys.check_constraints cc
WHERE
cc.is_ms_shipped = 0
AND cc.is_not_trusted = 1
)
SELECT
u.ConstraintType
, u.ConstraintName
, u.ConstraintTable
, u.ParentTable
, u.IsDisabled
, u.IsNotForReplication
, u.IsNotTrusted
, u.RowIndex
, 'RAISERROR( ''Now CHECKing {%i of %i)--> %s ON TABLE %s'', 0, 1'
+ ', ' + CAST( u.RowIndex AS VARCHAR(64))
+ ', ' + CAST( x.CommandCount AS VARCHAR(64))
+ ', ' + '''' + QUOTENAME( u.ConstraintName) + ''''
+ ', ' + '''' + QUOTENAME( u.ConstraintTable) + ''''
+ ') WITH NOWAIT;'
+ 'ALTER TABLE ' + QUOTENAME( u.ConstraintTable) + ' WITH CHECK CHECK CONSTRAINT ' + QUOTENAME( u.ConstraintName) + ';' AS FIX_SQL
FROM Untrusted u
CROSS APPLY (SELECT COUNT(*) AS CommandCount FROM Untrusted WHERE ConstraintType = u.ConstraintType) x
ORDER BY ConstraintType, ConstraintTable, ParentTable;
Remove numbering on x-axis or y-axis:
plot(1:10, xaxt='n')
plot(1:10, yaxt='n')
If you want to remove the labels as well:
plot(1:10, xaxt='n', ann=FALSE)
plot(1:10, yaxt='n', ann=FALSE)
This will work for ENUM type as default value
ALTER TABLE engagete_st.holidays add column `STATUS` ENUM('A', 'D') default 'A' AFTER `H_TYPE`;
HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);
I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. I am not a C# guru. So, it takes around 2 hours to resolve everything.
The following code works lately:
string connetionString = null;
connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";
using (MySqlConnection cn = new MySqlConnection(connetionString))
{
try
{
string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
cn.Open();
using (MySqlCommand cmd = new MySqlCommand(query, cn))
{
cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
cmd.ExecuteNonQuery();
}
}
catch (MySqlException ex)
{
MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
}
}
$(document).ready(function() {
$('#div2').hide(0);
$('#preview').on('click', function() {
$('#div1').hide(300, function() { // first hide div1
// then show div2
$('#div2').show(300);
});
});
});
You missed #
before div2
An example of an associated full GC also shows the collectors used for the old and permanent generations:
3.757: [Full GC [PSYoungGen: 2672K->0K(35584K)]
[ParOldGen: 3225K->5735K(43712K)] 5898K->5735K(79296K)
[PSPermGen: 13533K->13516K(27584K)], 0.0860402 secs]
Finally, breaking down one line of your example log output:
8109.128: [GC [PSYoungGen: 109884K->14201K(139904K)] 691015K->595332K(1119040K), 0.0454530 secs]