I had a problem on my Mac because one of the folder (directory) names in the path had a space in the name. BTW, the space was escaped by a \, but that was not understood by mySQL
Well this worked for me
rvm pkg install openssl
rvm reinstall 1.9.2 --with-openssl-dir=$rvm_path/usr
Something is wrong with openssl implementation of my ubuntu 12.04
The answer is: for no good reason whatsoever.
Contrary to its name, the XmlSerializer
class is used not only for serialization, but also for deserialization. It performs certain checks on your class to make sure that it will work, and some of those checks are only pertinent to deserialization, but it performs them all anyway, because it does not know what you intend to do later on.
The check that your class fails to pass is one of the checks that are only pertinent to deserialization. Here is what happens:
During deserialization, the XmlSerializer
class will need to create
instances of your type.
In order to create an instance of a type, a constructor of that type needs to be invoked.
If you did not declare a constructor, the compiler has already supplied a default parameterless constructor, but if you did declare a constructor, then that's the only constructor available.
So, if the constructor that you declared accepts parameters, then the only way to instantiate your class is by invoking that constructor which accepts parameters.
However, XmlSerializer
is not capable of invoking any constructor
except a parameterless constructor, because it does not know what
parameters to pass to constructors that accept parameters. So, it checks to see if your class has a parameterless constructor, and since it does not, it fails.
So, if the XmlSerializer
class had been written in such a way as to only perform the checks pertinent to serialization, then your class would pass, because there is absolutely nothing about serialization that makes it necessary to have a parameterless constructor.
As others have already pointed out, the quick solution to your problem is to simply add a parameterless constructor. Unfortunately, it is also a dirty solution, because it means that you cannot have any readonly
members initialized from constructor parameters.
In addition to all this, the XmlSerializer
class could have been written in such a way as to allow even deserialization of classes without parameterless constructors. All it would take would be to make use of "The Factory Method Design Pattern" (Wikipedia). From the looks of it, Microsoft decided that this design pattern is far too advanced for DotNet programmers, who apparently should not be unnecessarily confused with such things. So, DotNet programmers should better stick to parameterless constructors, according to Microsoft.
You can use microtime
and calculate the difference:
$time_pre = microtime(true);
exec(...);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
Here's the PHP docs for microtime
: http://php.net/manual/en/function.microtime.php
Add multiple classes:
$("p").addClass("class1 class2 class3");
or in cascade:
$("p").addClass("class1").addClass("class2").addClass("class3");
Very similar also to remove more classes:
$("p").removeClass("class1 class2 class3");
or in cascade:
$("p").removeClass("class1").removeClass("class2").removeClass("class3");
The facebook acess token looks similar too "1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc"
if you extract the middle part by using | to split you get
2.h1MTNeLqcLqw__.86400.129394400-605430316
then split again by -
the last part 605430316 is the user id.
Here is the C# code to extract the user id from the access token:
public long ParseUserIdFromAccessToken(string accessToken)
{
Contract.Requires(!string.isNullOrEmpty(accessToken);
/*
* access_token:
* 1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc
* |_______|
* |
* user id
*/
long userId = 0;
var accessTokenParts = accessToken.Split('|');
if (accessTokenParts.Length == 3)
{
var idPart = accessTokenParts[1];
if (!string.IsNullOrEmpty(idPart))
{
var index = idPart.LastIndexOf('-');
if (index >= 0)
{
string id = idPart.Substring(index + 1);
if (!string.IsNullOrEmpty(id))
{
return id;
}
}
}
}
return null;
}
WARNING: The structure of the access token is undocumented and may not always fit the pattern above. Use it at your own risk.
Update Due to changes in Facebook. the preferred method to get userid from the encrypted access token is as follows:
try
{
var fb = new FacebookClient(accessToken);
var result = (IDictionary<string, object>)fb.Get("/me?fields=id");
return (string)result["id"];
}
catch (FacebookOAuthException)
{
return null;
}
Here is what I find works
form name
Use a default select option
, for example...
<option value="-1" selected>Please Select</option>
So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.
This input
<input type="submit">
should be
<input name="Submit" type="submit" value="Submit">
whenever I use a form that fails, it is a failure due to the difference in calling the button name submit
and name as Submit
.
You should also set your enctype attribute for your form as forms fail on my web host if it's not set.
Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilter
Edit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter.
At the time of Building select device as iOS device. Then build the application. Select Product->Archive then select Share and save the .ipa file. Rename the ipa file to .zip and double click on zip file and you will get .app file in the folder. then compress the .app file of the application and iTunesArtwork image. it will be in the format .zip rename .zip to .ipa file.
Maybe I'm wrong but I think that SQL query from view is a bad idea
This is my way
In controller
$model = new SomeModel();
$items=ArrayHelper::map(TableName::find()->all(),'id','name');
return $this->render('view',['model'=>$model, 'items'=>$items])
And in View
<?= Html::activeDropDownList($model, 'item_id',$items) ?>
Or using ActiveForm
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'item_id')->dropDownList($items) ?>
<?php ActiveForm::end(); ?>
Just to add to RichieHindle's answer, check out Floatutorial, which walks you through how CSS floating and clearing works.
Use return statement anywhere you want to exit from function.
if(somecondtion)
return;
if(somecondtion)
return false;
The best option since office 2007 is using Open XML SDK for it. We used Word.Interop but it halt sometimes, and it is not recommend for Microsoft, to use it as a server side document formatting, so Open XML SDK lets you creates word documents on DOCX and Open XML formats very easily. It lets you going well with scability, confidence ( the files, if it is corrupted can be rebuild ), and another very fine characteristics.
Split it by space
and take first part like below. Hope this will help you.
var d = '12/12/1955 12:00:00 AM';
d = d.split(' ')[0];
console.log(d);
Apply the following steps:
mainactivity.java
public void openWindow2(View v) {
//call window2
setContentView(R.layout.window2);
}
}
try this
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="vertical" >
<TextView
android:id="@+id/textViewProfileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
import urllib
resource = urllib.urlopen("http://www.digimouth.com/news/media/2011/09/google-logo.jpg")
output = open("file01.jpg","wb")
output.write(resource.read())
output.close()
file01.jpg
will contain your image.
It's best if you judge on your own,
1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).
http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text
This Link is no more working so please watch this video for similar details Video
Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)
Some Variation: Some user find plugins useful for PHP coders on that
http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html
although, there are many plugins for Notepad Plus Plus ..
I am not sure of your requirements, nor I am promoter of either of these editors :)
So, judge on basis of your requirements, this should satisfy you query...
Yes we can add that both are evolving and changing fast..
you can use custom gallery control.. check this https://github.com/kilaka/ImageViewZoom use galleryTouch class from this..
You can also zoom by using MKCoordinateRegion and setting its span latitude & longitude delta. Below is a quick reference and here is the iOS reference. It won't do anything fancy but should allow you to set zoom when it draws the map.
MKCoordinateRegion region;
region.center.latitude = {desired lat};
region.center.longitude = {desired lng};
region.span.latitudeDelta = 1;
region.span.longitudeDelta = 1;
mapView.region = region;
Edit 1:
MKCoordinateRegion region;
region.center.latitude = {desired lat};
region.center.longitude = {desired lng};
region.span.latitudeDelta = 1;
region.span.longitudeDelta = 1;
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:TRUE];
Is it also possible to access the management port in a similar way, e.g.:
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {
@LocalServerPort
int randomServerPort;
@LocalManagementPort
int randomManagementPort;
thank you 'metakermit' for his good answer, but I think we can make it a bit better, for scroll to bottom, we should use this:
scrollToBottom = () => {
this.messagesEnd.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
}
but if you want to scroll top, you should use this:
scrollToTop = () => {
this.messagesEnd.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
}
and this codes are common:
componentDidMount() {
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
render () {
return (
<div>
<div className="MessageContainer" >
<div className="MessagesList">
{this.renderMessages()}
</div>
<div style={{ float:"left", clear: "both" }}
ref={(el) => { this.messagesEnd = el; }}>
</div>
</div>
</div>
);
}
what you are searching for is the Export-Csv file.csv
try using Get-Help Export-Csv to see whats possible
also Out-File -FilePath "file.csv"
will work
expr(1)
has a substr subcommand:
expr substr <string> <start-index> <length>
This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).
In an application level, here are something a developer can do:
From server side:
Check if load balancer(if you have),works correctly.
Turn slow TCP timeouts into 503 Fast Immediate response, if you load balancer work correctly, it should pick the working resource to serve, and it's better than hanging there with unexpected error massages.
Eg: If you are using node server, u can use toobusy from npm. Implementation something like:
var toobusy = require('toobusy');
app.use(function(req, res, next) {
if (toobusy()) res.send(503, "I'm busy right now, sorry.");
else next();
});
Why 503? Here are some good insights for overload: http://ferd.ca/queues-don-t-fix-overload.html
We can do some work in client side too:
Try to group calls in batch, reduce the traffic and total requests number b/w client and server.
Try to build a cache mid-layer to handle unnecessary duplicates requests.
I have tested it (Chrome) and it working for me( both [^]
and [^\0]
), by changing the dot (.
) by either [^\0]
or [^]
, because dot doesn't match line break (See here: http://www.regular-expressions.info/dot.html).
var ss= "<pre>aaaa\nbbb\nccc</pre>ddd";_x000D_
var arr= ss.match( /<pre[^\0]*?<\/pre>/gm );_x000D_
alert(arr); //Working
_x000D_
As I have seen it, java.util.Timer is the most used for implementing a timer.
For a repeating task:
new Timer().scheduleAtFixedRate(task, after, interval);
For a single run of a task:
new Timer().schedule(task, after);
task being the method to be executed
after the time to initial execution
(interval the time for repeating the execution)
Whenever you print any instance of your class, the default
toString
implementation of Object
class is called, which returns the representation that you are getting.
It contains two parts: - Type
and Hashcode
So, in student.Student@82701e that you get as output ->
student.Student
is the Type
, and82701e
is the HashCode
So, you need to override a toString
method in your Student
class to get required String representation
: -
@Override
public String toString() {
return "Student No: " + this.getStudentNo() +
", Student Name: " + this.getStudentName();
}
So, when from your main
class, you print your ArrayList
, it will invoke the toString
method for each instance, that you overrided
rather than the one in Object
class: -
List<Student> students = new ArrayList();
// You can directly print your ArrayList
System.out.println(students);
// Or, iterate through it to print each instance
for(Student student: students) {
System.out.println(student); // Will invoke overrided `toString()` method
}
In both the above cases, the toString
method overrided in Student
class will be invoked and appropriate representation of each instance will be printed.
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
You can use below SQL to read the BLOB Fields from table.
SELECT DBMS_LOB.SUBSTR(BLOB_FIELD_NAME) FROM TABLE_NAME;
I am using mysql and below syntax worked well for me,
ALTER TABLE table_name MODIFY col_name VARCHAR(12);
My machine showed me a BIOS update and I wondered if that has something to do with the sudden popping-up of this error. And after I did the update, the error was resolved and the solution built fine.
After successful login to cPanel, near to the phpMyAdmin
icon there is another icon MySQL Databases
; click on that.
That brings you to the database listing page.
In the action column you can find the delete database
option click on that to delete your database!
Assuming that you have a program running in the foreground, press ctrl-Z, then:
[1]+ Stopped myprogram
$ disown -h %1
$ bg 1
[1]+ myprogram &
$ logout
If there is only one job, then you don't need to specify the job number. Just use disown -h
and bg
.
You press ctrl-Z. The system suspends the running program, displays a job number and a "Stopped" message and returns you to a bash prompt.
You type the disown -h %1
command (here, I've used a 1
, but you'd use the job number that was displayed in the Stopped
message) which marks the job so it ignores the SIGHUP
signal (it will not be stopped by logging out).
Next, type the bg
command using the same job number; this resumes the running of the program in the background and a message is displayed confirming that.
You can now log out and it will continue running..
You could use Tiny-JSON
string json = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
IDictionary<string, string> dict = Tiny.Json.Decode<Dictionary<string, string>>(json);
You must place the label after a caption in order to for label
to store the table's number, not the chapter's number.
\begin{table} \begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |} -- cut -- \end{tabular} \caption{My table} \label{table:kysymys} \end{table} Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...
First of all, you would have to allocate memory:
char * S = new char[R.length() + 1];
then you can use strcpy
with S
and R.c_str()
:
std::strcpy(S,R.c_str());
You can also use R.c_str()
if the string doesn't get changed or the c string is only used once. However, if S
is going to be modified, you should copy the string, as writing to R.c_str()
results in undefined behavior.
Note: Instead of strcpy
you can also use str::copy
.
This syntax
--exclude-dir={dir1,dir2}
is expanded by the shell (e.g. Bash), not by grep
, into this:
--exclude-dir=dir1 --exclude-dir=dir2
Quoting will prevent the shell from expanding it, so this won't work:
--exclude-dir='{dir1,dir2}' <-- this won't work
The patterns used with --exclude-dir
are the same kind of patterns described in the man page for the --exclude
option:
--exclude=GLOB
Skip files whose base name matches GLOB (using wildcard matching).
A file-name glob can use *, ?, and [...] as wildcards, and \ to
quote a wildcard or backslash character literally.
The shell will generally try to expand such a pattern itself, so to avoid this, you should quote it:
--exclude-dir='dir?'
You can use the curly braces and quoted exclude patterns together like this:
--exclude-dir={'dir?','dir??'}
A pattern can span multiple path segments:
--exclude-dir='some*/?lse'
This would exclude a directory like topdir/something/else
.
another thing that worked for me after everything didn't - change "localhost" in config.inc.php to 127.0.0.1
Presumably from this site:
Internal Fragmentation Internal fragmentation occurs when the memory allocator leaves extra space empty inside of a block of memory that has been allocated for a client. This usually happens because the processor’s design stipulates that memory must be cut into blocks of certain sizes -- for example, blocks may be required to be evenly be divided by four, eight or 16 bytes. When this occurs, a client that needs 57 bytes of memory, for example, may be allocated a block that contains 60 bytes, or even 64. The extra bytes that the client doesn’t need go to waste, and over time these tiny chunks of unused memory can build up and create large quantities of memory that can’t be put to use by the allocator. Because all of these useless bytes are inside larger memory blocks, the fragmentation is considered internal.
External Fragmentation External fragmentation happens when the memory allocator leaves sections of unused memory blocks between portions of allocated memory. For example, if several memory blocks are allocated in a continuous line but one of the middle blocks in the line is freed (perhaps because the process that was using that block of memory stopped running), the free block is fragmented. The block is still available for use by the allocator later if there’s a need for memory that fits in that block, but the block is now unusable for larger memory needs. It cannot be lumped back in with the total free memory available to the system, as total memory must be contiguous for it to be useable for larger tasks. In this way, entire sections of free memory can end up isolated from the whole that are often too small for significant use, which creates an overall reduction of free memory that over time can lead to a lack of available memory for key tasks.
You must change the cmake C/CXX default FLAGS .
According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE}
put in the main CMakeLists.txt
one of :
For C
set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")
For C++
set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")
This will override the values defined in CMakeCache.txt
If you are using C#, you do not need to escape it.
One way is using a template function in your directive:
...
template: function(tElem, tAttrs){
return '<div ng-include="' + tAttrs.template + '" />';
}
...
In most cases a screen -RRx $username/
will suffice :)
If you still want to list all screens then put the following script in your path and call it screen or whatever you like:
#!/bin/bash
if [[ "$1" != "-ls-all" ]]; then
exec /usr/bin/screen "$@"
else
shopt -s nullglob
screens=(/var/run/screen/S-*/*)
if (( ${#screens[@]} == 0 )); then
echo "no screen session found in /var/run/screen"
else
echo "${screens[@]#*S-}"
fi
fi
It will behave exactly like screen except for showing all screen sessions, when giving the option -ls-all as first parameter.
Yes, I believe it should work and it can also be applied to other data types.
For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.
A lot of people come to this page with the goal of finding the webpack config and files in order to add their own configuration to them. Another way to achieve this without running npm run eject
is to use react-app-rewired. This allows you to overwrite your webpack config file without ejecting.
For the sake of completion:
apply(people[,-1], 2, function(x) sum(x))
#Height Weight
# 199 425
This may seem obvious, but run your site in Release mode, not Debug mode, when in production, and also during performance profiling. Release mode is much faster. Debug mode can hide performance problems in your own code.
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
I think you are looking for fmemopen(3)
:
#include <assert.h>
#include <stdio.h>
int main(void)
{
char buf[128] = { 0 };
FILE *fp = fmemopen(buf, sizeof(buf), "w");
assert(fp);
fprintf(fp, "Hello World!\n");
fprintf(fp, "%s also work, of course.\n", "Format specifiers");
fclose(fp);
puts(buf);
return 0;
}
If dynamic storage is more suitable for you use-case you could follow Liam's excellent suggestion about using open_memstream(3)
:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *buf;
size_t size;
FILE *fp = open_memstream(&buf, &size);
assert(fp);
fprintf(fp, "Hello World!\n");
fprintf(fp, "%s also work, of course.\n", "Format specifiers");
fclose(fp);
puts(buf);
free(buf);
return 0;
}
This happens because your click
handler fires before the value of the radio button changes. You need to listen to the change
event instead:
<input
type="radio"
name="optionsRadios"
id="optionsRadios2"
value=""
v-model="srStatus"
v-on:change="foo"> //here
Also, make sure you really want to call foo()
on ready... seems like maybe you don't actually want to do that.
ready:function(){
foo();
},
MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses.
You can get around this limit with the deprecated syntax:
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY 1 DESC
LIMIT 20
1, since it's the first column you want to group on.
To second Paul's response: yes, ctags (especially exuberant-ctags (http://ctags.sourceforge.net/)) is great. I have also added this to my vimrc, so I can use one tags file for an entire project:
set tags=tags;/
NULL-safe condition would looks like:
select * from table
where NOT (tester <=> 'username')
You can use the DirectoryIterator. Example from php Manual:
<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
?>
In my case Ubuntu 16.04
I have no crti.o
at all:
$ find /usr/ -name crti*
So I install developer libc6-dev package:
sudo apt-get install libc6-dev
if (A || B) { do something }
See the above definition where it states that a callback function is passed off to some other function and at some point it is called.
In C++ it is desirable to have callback functions call a classes method. When you do this you have access to the member data. If you use the C way of defining a callback you will have to point it to a static member function. This is not very desirable.
Here is how you can use callbacks in C++. Assume 4 files. A pair of .CPP/.H files for each class. Class C1 is the class with a method we want to callback. C2 calls back to C1's method. In this example the callback function takes 1 parameter which I added for the readers sake. The example doesn't show any objects being instantiated and used. One use case for this implementation is when you have one class that reads and stores data into temporary space and another that post processes the data. With a callback function, for every row of data read the callback can then process it. This technique cuts outs the overhead of the temporary space required. It is particularly useful for SQL queries that return a large amount of data which then has to be post-processed.
/////////////////////////////////////////////////////////////////////
// C1 H file
class C1
{
public:
C1() {};
~C1() {};
void CALLBACK F1(int i);
};
/////////////////////////////////////////////////////////////////////
// C1 CPP file
void CALLBACK C1::F1(int i)
{
// Do stuff with C1, its methods and data, and even do stuff with the passed in parameter
}
/////////////////////////////////////////////////////////////////////
// C2 H File
class C1; // Forward declaration
class C2
{
typedef void (CALLBACK C1::* pfnCallBack)(int i);
public:
C2() {};
~C2() {};
void Fn(C1 * pThat,pfnCallBack pFn);
};
/////////////////////////////////////////////////////////////////////
// C2 CPP File
void C2::Fn(C1 * pThat,pfnCallBack pFn)
{
// Call a non-static method in C1
int i = 1;
(pThat->*pFn)(i);
}
All you should need to do is:
# if the file in the right place isn't already committed:
git add <path to desired file>
# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai
# commit the merge:
git commit
Full credit to bchr02 for this answer. However, I had to modify it a bit to catch the scenario for lines that have */
(end of comment) followed by an empty line. The regex was matching the non empty line with */
.
New: (^(\r\n|\n|\r)$)|(^(\r\n|\n|\r))|^\s*$/gm
All I did is add ^
as second character to signify the start of line.
Here's what worked for me. My Python and Oracle versions are slightly different from yours, but the same approach should apply. Just make sure the cx_Oracle binary installer version matches your Oracle client and Python versions.
My versions:
Steps:
Source: oracle_python.bat
@echo off
set ORACLE_HOME=C:\your\path\to\instantclient_11_2
set PATH=%ORACLE_HOME%;%PATH%
Source: oracle_test.py
import cx_Oracle
conn_str = u'user/password@host:port/service'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute(u'select your_col_1, your_col_2 from your_table')
for row in c:
print row[0], "-", row[1]
conn.close()
Possible Issues:
The following code works fine for me:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
I had the same problem and the solution was to encapsulate the json inside this function
jsonp(
.... your json ...
)
I had the same error (which I find silly and not really helpful whatsoever as error messages go) and continued having problems, despite having a C compiler available.
Surprising, what ended up working for me was simply upgrading pip and setuptools to the most recent version. Hope this helps someone else out there.
The problem seems to be a mis-placed )
. In your sample you have the %
outside of the print()
, you should move it inside:
Use this:
print("%s. %s appears %s times." % (str(i), key, str(wordBank[key])))
https://issuetracker.google.com/issues/72479188 indicates that plugins sometimes can introduce "compile" dependencies and that's what triggers the warning. Probably just easiest to star that issue and wait until they fix it to point out which plugins are causing the issue.
You can calculate the difference in time in miliseconds using this method and get the outputs in seconds, minutes, hours, days, months and years.
You can download class from here: DateTimeDifference GitHub Link
long currentTime = System.currentTimeMillis(); long previousTime = (System.currentTimeMillis() - 864000000); //10 days ago Log.d("DateTime: ", "Difference With Second: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND)); Log.d("DateTime: ", "Difference With Minute: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100){ Log.d("DateTime: ", "There are more than 100 minutes difference between two dates."); }else{ Log.d("DateTime: ", "There are no more than 100 minutes difference between two dates."); }
I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:
String name;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
name = cursor.getString(cursor
.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
You might find the Semantic Versioning Specification useful.
df['Name']='abc'
will add the new column and set all rows to that value:
In [79]:
df
Out[79]:
Date, Open, High, Low, Close
0 01-01-2015, 565, 600, 400, 450
In [80]:
df['Name'] = 'abc'
df
Out[80]:
Date, Open, High, Low, Close Name
0 01-01-2015, 565, 600, 400, 450 abc
-- First Truncate temporary table SQL> TRUNCATE TABLE test_temp1; -- Then Drop temporary table SQL> DROP TABLE test_temp1;
Data type Range Storage
bigint -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) 8 Bytes
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes
smallint -2^15 (-32,768) to 2^15-1 (32,767) 2 Bytes
tinyint 0 to 255 1 Byte
Example
The following example creates a table using the bigint, int, smallint, and tinyint data types. Values are inserted into each column and returned in the SELECT statement.
CREATE TABLE dbo.MyTable
(
MyBigIntColumn bigint
,MyIntColumn int
,MySmallIntColumn smallint
,MyTinyIntColumn tinyint
);
GO
INSERT INTO dbo.MyTable VALUES (9223372036854775807, 214483647,32767,255);
GO
SELECT MyBigIntColumn, MyIntColumn, MySmallIntColumn, MyTinyIntColumn
FROM dbo.MyTable;
def LongestSubString(s1,s2):
left = 0
right =len(s2)
while(left<right):
if(s2[left] not in s1):
left = left+1
else:
if(s2[left:right] not in s1):
right = right - 1
else:
return(s2[left:right])
s1 = "pineapple"
s2 = "applc"
print(LongestSubString(s1,s2))
(1) Set the tabindex
attribute:
<div id="mydiv" tabindex="0" />
(2) Bind to keydown:
$('#mydiv').on('keydown', function(event) {
//console.log(event.keyCode);
switch(event.keyCode){
//....your actions for the keys .....
}
});
To set the focus on start:
$(function() {
$('#mydiv').focus();
});
To remove - if you don't like it - the div
focus border, set outline: none
in the CSS.
See the table of keycodes for more keyCode
possibilities.
All of the code assuming you use jQuery.
#If a linked server is not allowed by your dba, you can use OPENROWSET. Books Online will provide the syntax you need.
Correct Xpath
syntax is like:
//tagname[@value='name']
So you should write something like this:
findElement(By.xpath("//input[@test-id='test-username']"));
Specify negative value to spread value. This works for me:
box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
Forget using plt.title
and place the text directly with plt.text
. An over-exaggerated example is given below:
import pylab as plt
fig = plt.figure(figsize=(5,10))
figure_title = "Normal title"
ax1 = plt.subplot(1,2,1)
plt.title(figure_title, fontsize = 20)
plt.plot([1,2,3],[1,4,9])
figure_title = "Raised title"
ax2 = plt.subplot(1,2,2)
plt.text(0.5, 1.08, figure_title,
horizontalalignment='center',
fontsize=20,
transform = ax2.transAxes)
plt.plot([1,2,3],[1,4,9])
plt.show()
's up guys i read every single forum about this topic i still had problem (occurred trying to project from git)
after 4 hours and a lot of swearing i solved this issue by myself just by changing target framework setting in project properties (right click on project -> properties) -> application and changed target framework from .net core 3.0 to .net 5.0 i hope it will help anybody
happy coding gl hf nerds
Finally got it working after 1 hour struggle.
This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .
For a new WebApi 2 application example:
Postman (looks exactly, like below):
POST http://localhost:61402/api/values [Send]
Body
(*) raw JSON (application/json) v
"{ \"key1\": \"value1\" }"
The port 61402 or url /api/values above, may be different for you.
ValuesController.cs
using Newtonsoft.Json;
// ..
// POST api/values
[HttpPost]
public object Post([FromBody]string jsonString)
{
// add reference to Newtonsoft.Json
// using Newtonsoft.Json;
// jsonString to myJsonObj
var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
// value1 is myJsonObj[key1]
var valueOfkey1 = myJsonObj["key1"];
return myJsonObj;
}
All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.
install certificate in java linux
/opt/jdk(version)/bin/keytool -import -alias aliasname -file certificate.cer -keystore cacerts -storepass password
IEnumerable is refering to a collection but IQueryable is just a query and it will be generated inside a Expression Tree.we will run this query to get data from database.
Oh you can Output a message when using QT += gui
and CONFIG += console
.
You need printf("foo bar")
but cout << "foo bar"
doesn't works
You could drop any indexes on the table, then do your insert, and then recreate the indexes.
Updated 2020 Answer
Since Laravel 5.5 the @switch is built into the Blade. Use it as shown below.
@switch($login_error)
@case(1)
<span> `E-mail` input is empty!</span>
@break
@case(2)
<span>`Password` input is empty!</span>
@break
@default
<span>Something went wrong, please try again</span>
@endswitch
Older Answer
Unfortunately Laravel Blade does not have switch statement. You can use Laravel if else approach or use use plain PHP switch. You can use plain PHP in blade templates like in any other PHP application. Starting from Laravel 5.2 and up use @php statement.
Option 1:
@if ($login_error == 1)
`E-mail` input is empty!
@elseif ($login_error == 2)
`Password` input is empty!
@endif
Connection in APPConfig
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com" providerName="System.Data.SqlClient" />
</connectionStrings>
In Class.Cs
public string ConnectionString
{
get
{
return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
}
To the best of my knowledge, JavaScript's objects are garbage collected periodically when there are no references remaining to the object. It is something that happens automatically, but if you want to see more about how it works, at the C++ level, it makes sense to take a look at the WebKit or V8 source code
Typically you don't need to think about it, however, in older browsers, like IE 5.5 and early versions of IE 6, and perhaps current versions, closures would create circular references that when unchecked would end up eating up memory. In the particular case that I mean about closures, it was when you added a JavaScript reference to a dom object, and an object to a DOM object that referred back to the JavaScript object. Basically it could never be collected, and would eventually cause the OS to become unstable in test apps that looped to create crashes. In practice these leaks are usually small, but to keep your code clean you should delete the JavaScript reference to the DOM object.
Usually it is a good idea to use the delete keyword to immediately de-reference big objects like JSON data that you have received back and done whatever you need to do with it, especially in mobile web development. This causes the next sweep of the GC to remove that object and free its memory.
I just went through this. If you want to manually move your Eclipse installation you need to find and edit relative references in the following files.
Relative to Eclipse install dir:
For me in all these files there was a ../ reference to a .p2 folder in my home directory. Found them all using a simple grep:
grep '../../../../' * -R
Then just hit it with sed or manually go change it. In my case I moved it up one folder so easy fix:
grep -rl '../../../../' * -R | xargs sed -i 's/..\/..\/..\/..\//..\/..\/..\//g'
Now Eclipse runs fine again.
You can hide a part of JFrame that contains the swing controls which you want on another JFrame.
When the user clicks on a Jbutton the JFrame width increases and when he clicks on another same kind of Jbutton the JFrame comes to the default size.
JFrame myFrame = new JFrame("");
JButton button1 = new JButton("Basic");
JButton button2 = new JButton("More options");
// actionPerformed block code for button1 (Default size)
myFrame.setSize(400, 400);
// actionPerformed block code for button2 (Increase width)
myFrame.setSize(600, 400);
The Sara structure is a memory block containing the variables inside. There is nearly no difference between a classic declarations :
char first[20];
int age;
and a structure :
struct Person{
char first[20];
int age;
};
In both case, you are just allocating some memory to store variables, and in both case there will be 20+4 bytes reserved. In your case, Sara is just a memory block of 2x20 bytes.
The only difference is that with a structure, the memory is allocated as a single block, so if you take the starting address of Sara and jump 20 bytes, you'll find the "last" variable. This can be useful sometimes.
check http://publications.gbdirect.co.uk/c_book/chapter6/structures.html for more :) .
I use a simple/minimal solution, one line, cross browser, and works with legacy browsers as well:
/\bmyClass/.test(document.body.className) // notice the \b command for whole word 'myClass'
This method is great because does not require polyfills and if you use them for classList
it's much better in terms of performance. At least for me.
Update: I made a tiny polyfill that's an all round solution I use now:
function hasClass(element,testClass){
if ('classList' in element) { return element.classList.contains(testClass);
} else { return new Regexp(testClass).exec(element.className); } // this is better
//} else { return el.className.indexOf(testClass) != -1; } // this is faster but requires indexOf() polyfill
return false;
}
For the other class manipulation, see the complete file here.
Actually I use _ method names when I need to differ between parent and child class names. I've read some codes that used this way of creating parent-child classes. As an example I can provide this code:
class ThreadableMixin:
def start_worker(self):
threading.Thread(target=self.worker).start()
def worker(self):
try:
self._worker()
except tornado.web.HTTPError, e:
self.set_status(e.status_code)
except:
logging.error("_worker problem", exc_info=True)
self.set_status(500)
tornado.ioloop.IOLoop.instance().add_callback(self.async_callback(self.results))
...
and the child that have a _worker method
class Handler(tornado.web.RequestHandler, ThreadableMixin):
def _worker(self):
self.res = self.render_string("template.html",
title = _("Title"),
data = self.application.db.query("select ... where object_id=%s", self.object_id)
)
...
You could use somehting like
<ul>
<li><a href="#">Some text<span><br />Some text</span></a></li>
</ul>
and then in your css just set the span content bold and hide it with visibility: hidden, so that it keeps its dimensions. Then you can adjust margins of the following elements to make it fit properly.
I am not sure if this approach is SEO friendly though.
Brynner Ferreira, has brought a good point: storing a sibling key where expiration info resides. This way, if you have a large amount of keys, or if your values are large Json objects, you don't need to parse them to access the timestamp.
here follows an improved version:
/* removeStorage: removes a key from localStorage and its sibling expiracy key
params:
key <string> : localStorage key to remove
returns:
<boolean> : telling if operation succeeded
*/
function removeStorage(name) {
try {
localStorage.removeItem(name);
localStorage.removeItem(name + '_expiresIn');
} catch(e) {
console.log('removeStorage: Error removing key ['+ key + '] from localStorage: ' + JSON.stringify(e) );
return false;
}
return true;
}
/* getStorage: retrieves a key from localStorage previously set with setStorage().
params:
key <string> : localStorage key
returns:
<string> : value of localStorage key
null : in case of expired key or failure
*/
function getStorage(key) {
var now = Date.now(); //epoch time, lets deal only with integer
// set expiration for storage
var expiresIn = localStorage.getItem(key+'_expiresIn');
if (expiresIn===undefined || expiresIn===null) { expiresIn = 0; }
if (expiresIn < now) {// Expired
removeStorage(key);
return null;
} else {
try {
var value = localStorage.getItem(key);
return value;
} catch(e) {
console.log('getStorage: Error reading key ['+ key + '] from localStorage: ' + JSON.stringify(e) );
return null;
}
}
}
/* setStorage: writes a key into localStorage setting a expire time
params:
key <string> : localStorage key
value <string> : localStorage value
expires <number> : number of seconds from now to expire the key
returns:
<boolean> : telling if operation succeeded
*/
function setStorage(key, value, expires) {
if (expires===undefined || expires===null) {
expires = (24*60*60); // default: seconds for 1 day
} else {
expires = Math.abs(expires); //make sure it's positive
}
var now = Date.now(); //millisecs since epoch time, lets deal only with integer
var schedule = now + expires*1000;
try {
localStorage.setItem(key, value);
localStorage.setItem(key + '_expiresIn', schedule);
} catch(e) {
console.log('setStorage: Error setting key ['+ key + '] in localStorage: ' + JSON.stringify(e) );
return false;
}
return true;
}
The accepted answer does not work for databases that have large numbers of tables, e.g. Drupal databases. Instead, see the script here: https://stackoverflow.com/a/12917793/1507877 which does work on MySQL 5.5. CAUTION: Around line 11, there is a "WHERE table_schema = SCHEMA();" This should instead be "WHERE table_schema = 'INSERT NAME OF DB INTO WHICH IMPORT WILL OCCUR';"
Get the current (debug | release).
specified_configs=$$find(CONFIG, "\b(debug|release)\b")
build_subdir=$$last(specified_configs)
(May be multiple, so keep only last specified in the build):
Use it has the build subdir name
DESTDIR = $$PWD/build/$$build_subdir
There could be a very big misunderstanding related to string in the database are. Almost everyone has thought that database representation of numbers are more compact than for strings. They think that in db-s numbers are represented as in the memory. BUT it is not true. In most cases number representation is more close to A string like representation as to other.
The speed of using number or string is more dependent on the indexing then the type itself.
first you should be sure that selenium is installed in your system.
then install pycharm https://itsfoss.com/install-pycharm-ubuntu/
now if an of packages are not installed it will show red underlines. click on it and install from pycharm.
like for this case click on selenium option in import statement, there you would getting some options. click on install selenium. it will install and automatically run the code successfully if all your drivers are placed in proper directories.
This works for me:
var deviceXDPI = screen.deviceXDPI;
setInterval(function(){
if(screen.deviceXDPI != deviceXDPI){
deviceXDPI = screen.deviceXDPI;
... there was a resize ...
}
}, 500);
It's only needed on IE8. All the other browsers naturally generate a resize event.
You could use multiple background: linear-gradient(); calls, but try this:
If you want the images to be completely fused together where it doesn't look like the elements load separately due to separate HTTP requests then use this technique. Here we're loading two things on the same element that load simultaneously...
Just make sure you convert your pre-rendered 32-bit transparent png image/texture to base64 string first and use it within the background-image css call (in place of INSERTIMAGEBLOBHERE in this example).
I used this technique to fuse a wafer looking texture and other image data that's serialized with a standard rgba transparency / linear gradient css rule. Works better than layering multiple art and wasting HTTP requests which is bad for mobile. Everything is loaded client side with no file operation required, but does increase document byte size.
div.imgDiv {
background: linear-gradient(to right bottom, white, rgba(255,255,255,0.95), rgba(255,255,255,0.95), rgba(255,255,255,0.9), rgba(255,255,255,0.9), rgba(255,255,255,0.85), rgba(255,255,255,0.8) );
background-image: url("data:image/png;base64,INSERTIMAGEBLOBHERE");
}
From my experience, there is at least one clear advantage when using event.preventDefault() over using return false. Suppose you are capturing the click event on an anchor tag, otherwise which it would be a big problem if the user were to be navigated away from the current page. If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior.
$('a').click(function (e) {
// custom handling here
// oops...runtime error...where oh where will the href take me?
return false;
});
The benefit to using event.preventDefault() is that you can add this as the first line in the handler, thereby guaranteeing that the anchor's default behavior will not fire, regardless if the last line of the function is not reached (eg. runtime error).
$('a').click(function (e) {
e.preventDefault();
// custom handling here
// oops...runtime error, but at least the user isn't navigated away.
});
Use osenv.home()
. It's maintained by isaacs and I believe is used by npm itself.
In ~/.subversion/auth/svn.simple/
you should find a file with a long hexadecimal name. The password is in there in plaintext.
If there is more than one file you'll need to find that one that references the server you need the password for.
I had this issue start happening when debugging from one web project to a web service in the same solution. The web service was returning responses that the web project couldnt understand. It would kind of work again at some points, then stop again.
It was because there was not an explicit reference between these projects, so the web service was not getting built when hitting F5 to start debugging. Once I added that, the errors went away.
Unlike C++, Java does not support user defined operator overloading. The overloading is done internally in java.
We can take +
(plus) for example:
int a = 2 + 4;
string = "hello" + "world";
Here, plus adds two integer numbers and concatenates two strings. So we can say that Java supports internal operator overloading but not user defined.
To add to Matt wilson's answer I had a bunch of code-first entity classes but no database as I hadn't taken a backup. So I did the following on my Entity Framework project:
Open Package Manager console in Visual Studio and type the following:
Enable-Migrations
Add-Migration
Give your migration a name such as 'Initial' and then create the migration. Finally type the following:
Update-Database
Update-Database -Script -SourceMigration:0
The final command will create your database tables from your entity classes (provided your entity classes are well formed).
Assign the translucent theme to the activity that you want to make transparent in the Android manifest file of your project:
<activity
android:name="YOUR COMPLETE ACTIVITY NAME WITH PACKAGE"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
You can also try
interface IData{
id: number;
name:string;
}
let userTestStatus:Record<string,IData> = {
"0": { "id": 0, "name": "Available" },
"1": { "id": 1, "name": "Ready" },
"2": { "id": 2, "name": "Started" }
};
To check how record works: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt
Here in our case Record is used to declare an object whose key will be a string and whose value will be of type IData so now it will provide us intellisense when we will try to access its property and will throw type error in case we will try something like userTestStatus[0].nameee
You can use the partial function from functools like so.
from functools import partial
def perform(f):
f()
perform(Action1)
perform(partial(Action2, p))
perform(partial(Action3, p, r))
Also works with keywords
perform(partial(Action4, param1=p))
Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.
e.g. if you do this:
SELECT 1 / 2
you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.
e.g.
SELECT CAST(1 AS DECIMAL) / 2
gives 0.500000
List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();
String query = "SELECT rlink_id, COUNT(*)"
+ "FROM dbo.Locate "
+ "GROUP BY rlink_id ";
Statement stmt = yourconnection.createStatement();
try {
ResultSet rs4 = stmt.executeQuery(query);
while (rs4.next()) {
sids.add(rs4.getString(1));
lids.add(rs4.getString(2));
}
} finally {
stmt.close();
}
String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());
date.toLocaleDateString('en-US')
works great. Here's some more information on it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
May be a bit late but in my case i had to put the id in the 2nd anonymous object. This is because the 1st one is for route values i.e the return Url.
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { id = "signupform", role = "form" }))
Hope this can help somebody :)
There's a very short with "fast answer" here : How to test if remote TCP port is opened from Shell script?
nc -z <host> <port>; echo $?
I use it with 127.0.0.1 as "remote" address.
this returns "0" if the port is open and "1" if the port is closed
e.g.
nc -z 127.0.0.1 80; echo $?
-z Specifies that nc should just scan for listening daemons, without sending any data to them. It is an error to use this option in conjunc- tion with the -l option.
The SublimeText 3 Column-Select plugin should be all you need. Install that, then make sure you have something like the following in your 'Default (OSX).sublime-keymap' file:
// Column mode
{ "keys": ["ctrl+alt+up"], "command": "column_select", "args": {"by": "lines", "forward": false}},
{ "keys": ["ctrl+alt+down"], "command": "column_select", "args": {"by": "lines", "forward": true}},
{ "keys": ["ctrl+alt+pageup"], "command": "column_select", "args": {"by": "pages", "forward": false}},
{ "keys": ["ctrl+alt+pagedown"], "command": "column_select", "args": {"by": "pages", "forward": true}},
{ "keys": ["ctrl+alt+home"], "command": "column_select", "args": {"by": "all", "forward": false}},
{ "keys": ["ctrl+alt+end"], "command": "column_select", "args": {"by": "all", "forward": true}}
What exactly about it did not work for you?
$(".overdue").each( function() {
alert("Your book is overdue.");
});
Note that ".addClass()" works because addClass is a function defined on the jQuery object. You can't just plop any old function on the end of a selector and expect it to work.
Also, probably a bad idea to bombard the user with n popups (where n = the number of books overdue).
Perhaps use the size function:
alert( "You have " + $(".overdue").size() + " books overdue." );
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId()
.
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
From Pro C# 5.0 and the .NET 4.5 Framework
The ObservableCollection<T>
class is very useful in that it has the ability to inform external objects
when its contents have changed in some way (as you might guess, working with
ReadOnlyObservableCollection<T>
is very similar, but read-only in nature).
In many ways, working with
the ObservableCollection<T>
is identical to working with List<T>
, given that both of these classes
implement the same core interfaces. What makes the ObservableCollection<T>
class unique is that this
class supports an event named CollectionChanged
. This event will fire whenever a new item is inserted, a current item is removed (or relocated), or if the entire collection is modified.
Like any event, CollectionChanged is defined in terms of a delegate, which in this case is
NotifyCollectionChangedEventHandler
. This delegate can call any method that takes an object as the first parameter, and a NotifyCollectionChangedEventArgs
as the second. Consider the following Main()
method, which populates an observable collection containing Person objects and wires up the
CollectionChanged
event:
class Program
{
static void Main(string[] args)
{
// Make a collection to observe and add a few Person objects.
ObservableCollection<Person> people = new ObservableCollection<Person>()
{
new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
};
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;
// Now add a new item.
people.Add(new Person("Fred", "Smith", 32));
// Remove an item.
people.RemoveAt(0);
Console.ReadLine();
}
static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// What was the action that caused the event?
Console.WriteLine("Action for this event: {0}", e.Action);
// They removed something.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
Console.WriteLine("Here are the OLD items:");
foreach (Person p in e.OldItems)
{
Console.WriteLine(p.ToString());
}
Console.WriteLine();
}
// They added something.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
// Now show the NEW items that were inserted.
Console.WriteLine("Here are the NEW items:");
foreach (Person p in e.NewItems)
{
Console.WriteLine(p.ToString());
}
}
}
}
The incoming NotifyCollectionChangedEventArgs
parameter defines two important properties,
OldItems
and NewItems
, which will give you a list of items that were currently in the collection before the event fired, and the new items that were involved in the change. However, you will want to examine these lists only under the correct circumstances. Recall that the CollectionChanged event can fire when
items are added, removed, relocated, or reset. To discover which of these actions triggered the event,
you can use the Action property of NotifyCollectionChangedEventArgs. The Action property can be
tested against any of the following members of the NotifyCollectionChangedAction
enumeration:
public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}
(a little bit late, but could be useful)
Only trust PHP_INT_MAX and PHP_INT_SIZE, this value vary on your arch (32/64 bits) and your OS...
Any other "guess" or "hint" can be false.
You haven't specified any keyframes. I made it work here.
div {
margin: 20px;
width: 100px;
height: 100px;
background: #f00;
-webkit-animation: spin 4s infinite linear;
}
@-webkit-keyframes spin {
0% {-webkit-transform: rotate(0deg);}
100% {-webkit-transform: rotate(360deg);}
}
You can actually do lots of really cool stuff with this. Here is one I made earlier.
:)
N.B. You can skip having to write out all the prefixes if you use -prefix-free.
I had an issue with duplicate entries in one table itself. Below is the approaches were working for me. It has also been advocated by @sibaz.
Finally I solved it using the below queries:
The select query is saved in a temp table
IF OBJECT_ID(N'tempdb..#New_format_donor_temp', N'U') IS NOT NULL
DROP TABLE #New_format_donor_temp;
select *
into #New_format_donor_temp
from DONOR_EMPLOYMENTS
where DONOR_ID IN (
1, 2
)
-- Test New_format_donor_temp
-- SELECT *
-- FROM #New_format_donor_temp;
The temp table is joined in the update query.
UPDATE de
SET STATUS_CD=de_new.STATUS_CD, STATUS_REASON_CD=de_new.STATUS_REASON_CD, TYPE_CD=de_new.TYPE_CD
FROM DONOR_EMPLOYMENTS AS de
INNER JOIN #New_format_donor_temp AS de_new ON de_new.EMP_NO = de.EMP_NO
WHERE
de.DONOR_ID IN (
3, 4
)
I not very experienced with SQL please advise any better approach you know.
Above queries are for MySql server.
You can set
<table>
<tr style="visibility: hidden"></tr>
</table>
My problem and solution was different and I thought I should post it here so that future readers can save their head from banging to the wall.
I was allocating different xib to same UIVIewController and even after searching everywhere I couldn't find how to correct it. Then I checked my AppDelegate where I was calling initWithNibName
and can see that while copying the code, I changed the xib name, but forgot to change UIViewController
class. So if none of the solution works for you, check your initWithNibName
method.
I found that my problem related to the actual registration of the DLL.
Use FormulaR1C1:
Cells((1,3),(10,3)).FormulaR1C1 = "=RC[-2]+RC[-1]"
Unlike Formula, FormulaR1C1 has relative referencing.
Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.
In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.
You can find the official list here: http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx
All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with _PTR (DWORD_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).
In my experience there are two places where we want to use uint8_t to mean 8 bits (and uint16_t, etc) and where we can have fields smaller than 8 bits. Both places are where space matters and we often need to look at a raw dump of the data when debugging and need to be able to quickly determine what it represents.
The first is in RF protocols, especially in narrow-band systems. In this environment we may need to pack as much information as we can into a single message. The second is in flash storage where we may have very limited space (such as in embedded systems). In both cases we can use a packed data structure in which the compiler will take care of the packing and unpacking for us:
#pragma pack(1)
typedef struct {
uint8_t flag1:1;
uint8_t flag2:1;
padding1 reserved:6; /* not necessary but makes this struct more readable */
uint32_t sequence_no;
uint8_t data[8];
uint32_t crc32;
} s_mypacket __attribute__((packed));
#pragma pack()
Which method you use depends on your compiler. You may also need to support several different compilers with the same header files. This happens in embedded systems where devices and servers can be completely different - for example you may have an ARM device that communicates with an x86 Linux server.
There are a few caveats with using packed structures. The biggest gotcha is that you must avoid dereferencing the address of a member. On systems with mutibyte aligned words, this can result in a misaligned exception - and a coredump.
Some folks will also worry about performance and argue that using these packed structures will slow down your system. It is true that, behind the scenes, the compiler adds code to access the unaligned data members. You can see that by looking at the assembly code in your IDE.
But since packed structures are most useful for communication and data storage then the data can be extracted into a non-packed representation when working with it in memory. Normally we do not need to be working with the entire data packet in memory anyway.
Here is some relevant discussion:
pragma pack(1) nor __attribute__ ((aligned (1))) works
Is gcc's __attribute__((packed)) / #pragma pack unsafe?
http://solidsmoke.blogspot.ca/2010/07/woes-of-structure-packing-pragma-pack.html
You can do it like this
mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]
mylist = [mylist[i] for i in myorder]
print(mylist) # prints: ['d', 'c', 'a', 'b', 'e']
int count = 0;
foreach (ListViewItem lvi in listView.Items)
{
if(++count > 50) break;
}
In Linux, first of all execute sudo service docker start
in terminal.
Use crosstab()
from the tablefunc module.
SELECT * FROM crosstab(
$$SELECT user_id, user_name, rn, email_address
FROM (
SELECT u.user_id, u.user_name, e.email_address
, row_number() OVER (PARTITION BY u.user_id
ORDER BY e.creation_date DESC NULLS LAST) AS rn
FROM usr u
LEFT JOIN email_tbl e USING (user_id)
) sub
WHERE rn < 4
ORDER BY user_id
$$
, 'VALUES (1),(2),(3)'
) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);
I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:
Detailed explanation and instructions here:
And in particular, for "extra columns":
The special difficulties here are:
The lack of key names.
-> We substitute with row_number()
in a subquery.
The varying number of emails.
-> We limit to a max. of three in the outer SELECT
and use crosstab()
with two parameters, providing a list of possible keys.
Pay attention to NULLS LAST
in the ORDER BY
.
The accepted answer being said, It is missing some explanations. For example, what is the difference between a uni-directional and a bi-directional association? In the provided example, both do exist. ( Both '5's in the arrows)
If looking for a more complete answer and have more time, here is a thorough explanation.
Just give full path to exclusion file: eg..
-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt
In this example the file would be located " C:\list-of-excluded-files.txt "
or...
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt
In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "
Full path fixes syntax error.
This command works for me:
Command:
mysql --host=localhost -uroot -proot
It's very simple, first convert the number to string using the toString() method in JavaScript and then use split() method to convert the string to an array of individual characters.
For example, the number is num, then
const numberDigits = num.toString().split('');
Convert Date To String
Use name Space
using System.Globalization;
Code
string date = DateTime.ParseExact(datetext.Text, "dd-MM-yyyy", CultureInfo.InstalledUICulture).ToString("yyyy-MM-dd");
var a = 'something' + Array(10).fill('\xa0').join('') + 'something'
number inside Array(10)
can be changed to needed number of spaces
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);
Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});
With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.
Example with no parameters:
delegate void NewEventHandler();
public event NewEventHandler OnEventHappens;
And from another class, you can subscribe to
otherClass.OnEventHappens += ExecuteThisFunctionWhenEventHappens;
And declare that function with no parameters.
I had massive problems with getting any of those scripts to work with sending mail in powershell. Turned out you need to create an app-password for your gmail-account to authenticate in the script. Now it works flawlessly!
$scope.rtGo = function(){
$window.sessionStorage.removeItem('message');
$window.sessionStorage.removeItem('status');
}
As Martin Thoma has said, you need to normally apply thresholding. But you can do this using simple vectorization which will run much faster than the for loop that is used in that answer.
The code below converts the pixels of an image into 0 (black) and 1 (white).
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
#Pixels higher than this will be 1. Otherwise 0.
THRESHOLD_VALUE = 200
#Load image and convert to greyscale
img = Image.open("photo.png")
img = img.convert("L")
imgData = np.asarray(img)
thresholdedData = (imgData > THRESHOLD_VALUE) * 1.0
plt.imshow(thresholdedData)
plt.show()
This code is to solve our problem to set unique key for existing table
alter ignore table ioni_groups add unique (group_name);
yes It is possible.. returns type can be different only if parent class method return type is
a super type of child class method return type..
means
class ParentClass {
public Circle() method1() {
return new Cirlce();
}
}
class ChildClass extends ParentClass {
public Square method1() {
return new Square();
}
}
Class Circle {
}
class Square extends Circle {
}
public enum EXIT_CODE {
A(104), B(203);
private int numVal;
EXIT_CODE(int numVal) {
this.numVal = numVal;
}
public int getNumVal() {
return numVal;
}
}
(function($) {_x000D_
$(document).ready(function() {_x000D_
$('#data').click(function(e) {_x000D_
e.preventDefault();_x000D_
$.each($("#keywords").val().split("\n"), function(e, element) {_x000D_
alert(element);_x000D_
});_x000D_
});_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<textarea id="keywords">Hello_x000D_
World</textarea>_x000D_
<input id="data" type="button" value="submit">
_x000D_
For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.
import java.util.Random;
public class CodeWithPrivateMethod {
public void meaningfulPublicApi() {
if (doTheGamble("Whatever", 1 << 3)) {
throw new RuntimeException("boom");
}
}
private boolean doTheGamble(String whatever, int binary) {
Random random = new Random(System.nanoTime());
boolean gamble = random.nextBoolean();
return gamble;
}
}
The test class looks as follows:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;
@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
private CodeWithPrivateMethod classToTest;
@Test(expected = RuntimeException.class)
public void when_gambling_is_true_then_always_explode() throws Exception {
classToTest = PowerMockito.spy(classToTest);
doReturn(true).when(classToTest, "doTheGamble", anyString(), anyInt());
classToTest.meaningfulPublicApi();
}
}
This should work:
for /F "tokens=*" %i in ('temperature') do prismcom.exe usb %i
If running in a batch file, you need to use %%i
instead of just %i
(in both places).
For anyone who is looking for solutions here, I had a similar issue with C++: malloc(): smallbin double linked list corrupted:
This was due to a function not returning a value it was supposed to.
std::vector<Object> generateStuff(std::vector<Object>& target> {
std::vector<Object> returnValue;
editStuff(target);
// RETURN MISSING
}
Don't know why this was able to compile after all. Probably there was a warning about it.
optimized from spacedrop answer ...
ls $(pwd)/*
and you can use ls options
ls -alrt $(pwd)/*
It means you're trying to concatenate a string with something that is None
.
None is the "null" of Python, and NoneType
is its type.
This code will raise the same kind of error:
>>> bar = "something"
>>> foo = None
>>> print foo + bar
TypeError: cannot concatenate 'str' and 'NoneType' objects
If you'd like to avoid hard-coding a specific design with css, but rather rely on the browser's default button, you can use the following css.
a.button {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
}
Notice that it probably won't work on IE.
The scenarios that you have mentioned are not of overloading, you are just concatenating different variables with a String.
System.out.print("Hello World");
System.out.print("My name is" + foo);
System.out.print("Sum of " + a + "and " + b + "is " + c);
System.out.print("Total USD is " + usd);
in all of these cases, you are only calling print(String s) because when something is concatenated with a string it gets converted to a String by calling the toString() of that object, and primitives are directly concatenated. However if you want to know of different signatures then yes print() is overloaded for various arguments.
Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.com/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
You can implement throwing exceptions on mysql query fail on your own. What you need is to write a wrapper for mysql_query function, e.g.:
// user defined. corresponding MySQL errno for duplicate key entry
const MYSQL_DUPLICATE_KEY_ENTRY = 1022;
// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}
function my_mysql_query($query, $conn=false) {
$res = mysql_query($query, $conn);
if (!$res) {
$errno = mysql_errno($conn);
$error = mysql_error($conn);
switch ($errno) {
case MYSQL_DUPLICATE_KEY_ENTRY:
throw new MySQLDuplicateKeyException($error, $errno);
break;
default:
throw MySQLException($error, $errno);
break;
}
}
// ...
// doing something
// ...
if ($something_is_wrong) {
throw new Exception("Logic exception while performing query result processing");
}
}
try {
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
}
catch (MySQLDuplicateKeyException $e) {
// duplicate entry exception
$e->getMessage();
}
catch (MySQLException $e) {
// other mysql exception (not duplicate key entry)
$e->getMessage();
}
catch (Exception $e) {
// not a MySQL exception
$e->getMessage();
}
This question has been out here a long time, but I wanted to contribute how I usually iterate through a JSON object. In the example below, I've shown a hard-coded string that contains the JSON, but the JSON string could just as easily have come from a web service or a file.
import json
def main():
# create a simple JSON array
jsonString = '{"key1":"value1","key2":"value2","key3":"value3"}'
# change the JSON string into a JSON object
jsonObject = json.loads(jsonString)
# print the keys and values
for key in jsonObject:
value = jsonObject[key]
print("The key and value are ({}) = ({})".format(key, value))
pass
if __name__ == '__main__':
main()
Have you tried to correct the syntax like this?:
create or replace procedure temp_proc AS
begin
DBMS_OUTPUT.PUT_LINE('Test');
end;
I had the same issue after trying many combination I had this working note I have compatibility checked for intranet
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<head runat="server">
Some of the codes are string heavy. Instead of creating substring which creates new object, we can just pass on indexes in recursive calls like below:
private static boolean isPalindrome(String str, int left, int right) {
if(left >= right) {
return true;
}
else {
if(str.charAt(left) == str.charAt(right)) {
return isPalindrome(str, ++left, --right);
}
else {
return false;
}
}
}
public static void main(String []args){
String str = "abcdcbb";
System.out.println(isPalindrome(str, 0, str.length()-1));
}
Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from
result.replace(/"/g,'"')
to
result.replace(/"/g,'"')
Instead of this I use that:
result.replace(/("\;)/g,"\"")
By this notation it works.
To increase the font size of netbeans 7.3.1 and 7.3 , you go from menu Tools>>Options>>"Fonts & Colors" (is an inner menu in the dialog window of Options)
At the "Syntax" tab ,every entry in the "Category:" list-box ,you will notice that the font has the value "Inherited". If you find in the "Category" list-box the entry with the name "Default" and change the font value of that, you will affect the font size of your editor, because everything is inherited from "Default" entry .
Another method is to increase temporary the font of the editor by a combination of keys. To find what are the keys go to the "Options" dialog window by Tools>> Options and then choose the "Keymap" menu entry and then in the "Search" textbox type "zoom text" and it will show you what combinations of keys for zooming in /out.
for example mine is the combination of "alt" key + mouse wheel up/down
I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.
I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.
I hope this helps.
convertToArray(file_get_content($filename));
function convertToArray(string $content): array
{
$data = str_getcsv($content,"\n");
array_walk($data, function(&$a) use ($data) {
$a = str_getcsv($a);
});
return $data;
}
This one cares about the order without too much hassle (OrderdDict & others). Probably not the most Pythonic way, nor shortest way, but does the trick:
def remove_duplicates(list):
''' Removes duplicate items from a list '''
singles_list = []
for element in list:
if element not in singles_list:
singles_list.append(element)
return singles_list
Try below code
public enum SalaryHeadMasterEnum {
BASIC_PAY("basic pay"),
MEDICAL_ALLOWANCE("Medical Allowance");
private String name;
private SalaryHeadMasterEnum(String stringVal) {
name=stringVal;
}
public String toString(){
return name;
}
public static String getEnumByString(String code){
for(SalaryHeadMasterEnum e : SalaryHeadMasterEnum.values()){
if(e.name.equals(code)) return e.name();
}
return null;
}
}
Now you can use below code to retrieve the Enum by Value
SalaryHeadMasterEnum.getEnumByString("Basic Pay")
Use Below code to get ENUM as String
SalaryHeadMasterEnum.BASIC_PAY.name()
Use below code to get string Value for enum
SalaryHeadMasterEnum.BASIC_PAY.toString()
There is now (as of v1.10.7) a fourth way to instantiate mocks, which is using a JUnit4 rule called MockitoRule.
@RunWith(JUnit4.class) // or a different runner of your choice
public class YourTest
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Mock public YourMock yourMock;
@Test public void yourTestMethod() { /* ... */ }
}
JUnit looks for subclasses of TestRule annotated with @Rule, and uses them to wrap the test Statements that the Runner provides. The upshot of this is that you can extract @Before methods, @After methods, and even try...catch wrappers into rules. You can even interact with these from within your test, the way that ExpectedException does.
MockitoRule behaves almost exactly like MockitoJUnitRunner, except that you can use any other runner, such as Parameterized (which allows your test constructors to take arguments so your tests can be run multiple times), or Robolectric's test runner (so its classloader can provide Java replacements for Android native classes). This makes it strictly more flexible to use in recent JUnit and Mockito versions.
In summary:
Mockito.mock()
: Direct invocation with no annotation support or usage validation.MockitoAnnotations.initMocks(this)
: Annotation support, no usage validation.MockitoJUnitRunner
: Annotation support and usage validation, but you must use that runner.MockitoRule
: Annotation support and usage validation with any JUnit runner.See also: How JUnit @Rule works?
Here's a shorter version without the subselect:
SELECT COUNT(DISTINCT DocumentId, DocumentSessionId) FROM DocumentOutputItems
It works fine in MySQL, and I think that the optimizer has an easier time understanding this one.
Edit: Apparently I misread MSSQL and MySQL - sorry about that, but maybe it helps anyway.
Here there is my example of animation a staff list with expand a description.
<html>
<head>
<style>
.staff { margin:10px 0;}
.staff-block{ float: left; width:48%; padding-left: 10px; padding-bottom: 10px;}
.staff-title{ font-family: Verdana, Tahoma, Arial, Serif; background-color: #1162c5; color: white; padding:4px; border: solid 1px #2e3d7a; border-top-left-radius:3px; border-top-right-radius: 6px; font-weight: bold;}
.staff-name { font-family: Myriad Web Pro; font-size: 11pt; line-height:30px; padding: 0 10px;}
.staff-name:hover { background-color: silver !important; cursor: pointer;}
.staff-section { display:inline-block; padding-left: 10px;}
.staff-desc { font-family: Myriad Web Pro; height: 0px; padding: 3px; overflow:hidden; background-color:#def; display: block; border: solid 1px silver;}
.staff-desc p { text-align: justify; margin-top: 5px;}
.staff-desc img { margin: 5px 10px 5px 5px; float:left; height: 185px; }
</style>
</head>
<body>
<!-- START STAFF SECTION -->
<div class="staff">
<div class="staff-block">
<div class="staff-title">Staff</div>
<div class="staff-section">
<div class="staff-name">Maria Beavis</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Maria earned a Bachelor of Commerce degree from McGill University in 2006 with concentrations in Finance and International Business. She has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007.</p>
</div>
<div class="staff-name">Diana Smitt</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Diana joined the Diana Smitt Group to help contribute to its ongoing commitment to provide superior investement advice and exceptional service. She has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses.</p>
</div>
<div class="staff-name">Mike Ford</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Mike: A graduate of École des hautes études commerciales (HEC Montreal), Guillaume holds the Chartered Investment Management designation (CIM). After having been active in the financial services industry for 4 years at a leading competitor he joined the Mike Ford Group.</p>
</div>
</div>
</div>
<div class="staff-block">
<div class="staff-title">Technical Advisors</div>
<div class="staff-section">
<div class="staff-name">TA Elvira Bett</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Elvira has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007. Laura works directly with Caroline Hild, aiding in revising client portfolios, maintaining investment objectives, and executing client trades.</p>
</div>
<div class="staff-name">TA Sonya Rosman</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Sonya has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses through the Canadian Securities Institute. She recently completed her Wealth Management Essentials course and became an Investment Associate.</p>
</div>
<div class="staff-name">TA Tim Herson</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Tim joined his father’s group in order to continue advising affluent families in Quebec. He is currently President of the Mike Ford Professionals Association and a member of various other organisations.</p>
</div>
</div>
</div>
</div>
<!-- STOP STAFF SECTION -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript"><!--
//<![CDATA[
$('.staff-name').hover(function() {
$(this).toggleClass('hover');
});
var lastItem;
$('.staff-name').click(function(currentItem) {
var currentItem = $(this);
if ($(this).next().height() == 0) {
$(lastItem).css({'font-weight':'normal'});
$(lastItem).next().animate({height: '0px'},400,'swing');
$(this).css({'font-weight':'bold'});
$(this).next().animate({height: '300px',opacity: 1},400,'swing');
} else {
$(this).css({'font-weight':'normal'});
$(this).next().animate({height: '0px',opacity: 1},400,'swing');
}
lastItem = $(this);
});
//]]>
--></script>
</body></html>
How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...
Set<String> strSet = strList.stream().collect(Collectors.toSet());
Is the easiest way to remove your duplicates.
In C++, the size of int
isn't specified explicitly. It just tells you that it must be at least the size of short int
, which must be at least as large as signed char
. The size of char
in bits isn't specified explicitly either, although sizeof(char) is defined to be 1. If you want a 64 bit int, C++11 specifies long long
to be at least 64 bits.
You could use IIF
statement like in the next example:
SELECT
IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
TABLE_NAME
Here are few steps that must be followed carefully
Create a folder named config inside C:\wamp\apps\phpmyadmin, the folder inside apps may have different name like phpmyadmin3.2.0.1
Return to your browser in phpmyadmin setup tab, and click New server.
Change the authentication type to ‘cookie’ and leave the username and password field empty but if you change the authentication type to ‘config’ enter the password for username root.
It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.
You can use the following approach.
$data = [
['user_id'=>'Coder 1', 'subject_id'=> 4096],
['user_id'=>'Coder 2', 'subject_id'=> 2048],
//...
];
Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach
In your case you already have the data within the $query
variable.
Security researchers Jean-Baptiste Bédrune and Jean Sigwald presented how to do this at Hack-in-the-box Amsterdam 2011.
Since then, Apple has released an iOS Security Whitepaper with more details about keys and algorithms, and Charlie Miller et al. have released the iOS Hacker’s Handbook, which covers some of the same ground in a how-to fashion. When iOS 10 first came out there were changes to the backup format which Apple did not publicize at first, but various people reverse-engineered the format changes.
The great thing about encrypted iPhone backups is that they contain things like WiFi passwords that aren’t in regular unencrypted backups. As discussed in the iOS Security Whitepaper, encrypted backups are considered more “secure,” so Apple considers it ok to include more sensitive information in them.
An important warning: obviously, decrypting your iOS device’s backup
removes its encryption. To protect your privacy and security, you should
only run these scripts on a machine with full-disk encryption. While it
is possible for a security expert to write software that protects keys in
memory, e.g. by using functions like VirtualLock()
and
SecureZeroMemory()
among many other things, these
Python scripts will store your encryption keys and passwords in strings to
be garbage-collected by Python. This means your secret keys and passwords
will live in RAM for a while, from whence they will leak into your swap
file and onto your disk, where an adversary can recover them. This
completely defeats the point of having an encrypted backup.
The iOS Security Whitepaper explains the fundamental concepts of per-file keys, protection classes, protection class keys, and keybags better than I can. If you’re not already familiar with these, take a few minutes to read the relevant parts.
Now you know that every file in iOS is encrypted with its own random per-file encryption key, belongs to a protection class, and the per-file encryption keys are stored in the filesystem metadata, wrapped in the protection class key.
To decrypt:
Decode the keybag stored in the BackupKeyBag
entry of
Manifest.plist
. A high-level overview of this structure is given in
the whitepaper. The iPhone Wiki
describes the binary format: a 4-byte string type field, a 4-byte
big-endian length field, and then the value itself.
The important values are the PBKDF2 ITER
ations and SALT
, the double
protection salt DPSL
and iteration count DPIC
, and then for each
protection CLS
, the WPKY
wrapped key.
Using the backup password derive a 32-byte key using the correct PBKDF2
salt and number of iterations. First use a SHA256 round with DPSL
and
DPIC
, then a SHA1 round with ITER
and SALT
.
Unwrap each wrapped key according to RFC 3394.
Decrypt the manifest database by pulling the 4-byte protection class and longer key from the ManifestKey
in Manifest.plist
, and unwrapping it. You now have a
SQLite database with all file metadata.
For each file of interest, get the class-encrypted per-file encryption
key and protection class code by looking in the Files.file
database
column for a binary plist containing EncryptionKey
and
ProtectionClass
entries. Strip the initial four-byte length tag from
EncryptionKey
before using.
Then, derive the final decryption key by unwrapping it with the class key that was unwrapped with the backup password. Then decrypt the file using AES in CBC mode with a zero IV.
First you’ll need some library dependencies. If you’re on a mac using a homebrew-installed Python 2.7 or 3.7, you can install the dependencies with:
CFLAGS="-I$(brew --prefix)/opt/openssl/include" \
LDFLAGS="-L$(brew --prefix)/opt/openssl/lib" \
pip install biplist fastpbkdf2 pycrypto
In runnable source code form, here is how to decrypt a single preferences file from an encrypted iPhone backup:
#!/usr/bin/env python3.7
# coding: UTF-8
from __future__ import print_function
from __future__ import division
import argparse
import getpass
import os.path
import pprint
import random
import shutil
import sqlite3
import string
import struct
import tempfile
from binascii import hexlify
import Crypto.Cipher.AES # https://www.dlitz.net/software/pycrypto/
import biplist
import fastpbkdf2
from biplist import InvalidPlistException
def main():
## Parse options
parser = argparse.ArgumentParser()
parser.add_argument('--backup-directory', dest='backup_directory',
default='testdata/encrypted')
parser.add_argument('--password-pipe', dest='password_pipe',
help="""\
Keeps password from being visible in system process list.
Typical use: --password-pipe=<(echo -n foo)
""")
parser.add_argument('--no-anonymize-output', dest='anonymize',
action='store_false')
args = parser.parse_args()
global ANONYMIZE_OUTPUT
ANONYMIZE_OUTPUT = args.anonymize
if ANONYMIZE_OUTPUT:
print('Warning: All output keys are FAKE to protect your privacy')
manifest_file = os.path.join(args.backup_directory, 'Manifest.plist')
with open(manifest_file, 'rb') as infile:
manifest_plist = biplist.readPlist(infile)
keybag = Keybag(manifest_plist['BackupKeyBag'])
# the actual keys are unknown, but the wrapped keys are known
keybag.printClassKeys()
if args.password_pipe:
password = readpipe(args.password_pipe)
if password.endswith(b'\n'):
password = password[:-1]
else:
password = getpass.getpass('Backup password: ').encode('utf-8')
## Unlock keybag with password
if not keybag.unlockWithPasscode(password):
raise Exception('Could not unlock keybag; bad password?')
# now the keys are known too
keybag.printClassKeys()
## Decrypt metadata DB
manifest_key = manifest_plist['ManifestKey'][4:]
with open(os.path.join(args.backup_directory, 'Manifest.db'), 'rb') as db:
encrypted_db = db.read()
manifest_class = struct.unpack('<l', manifest_plist['ManifestKey'][:4])[0]
key = keybag.unwrapKeyForClass(manifest_class, manifest_key)
decrypted_data = AESdecryptCBC(encrypted_db, key)
temp_dir = tempfile.mkdtemp()
try:
# Does anyone know how to get Python’s SQLite module to open some
# bytes in memory as a database?
db_filename = os.path.join(temp_dir, 'db.sqlite3')
with open(db_filename, 'wb') as db_file:
db_file.write(decrypted_data)
conn = sqlite3.connect(db_filename)
conn.row_factory = sqlite3.Row
c = conn.cursor()
# c.execute("select * from Files limit 1");
# r = c.fetchone()
c.execute("""
SELECT fileID, domain, relativePath, file
FROM Files
WHERE relativePath LIKE 'Media/PhotoData/MISC/DCIM_APPLE.plist'
ORDER BY domain, relativePath""")
results = c.fetchall()
finally:
shutil.rmtree(temp_dir)
for item in results:
fileID, domain, relativePath, file_bplist = item
plist = biplist.readPlistFromString(file_bplist)
file_data = plist['$objects'][plist['$top']['root'].integer]
size = file_data['Size']
protection_class = file_data['ProtectionClass']
encryption_key = plist['$objects'][
file_data['EncryptionKey'].integer]['NS.data'][4:]
backup_filename = os.path.join(args.backup_directory,
fileID[:2], fileID)
with open(backup_filename, 'rb') as infile:
data = infile.read()
key = keybag.unwrapKeyForClass(protection_class, encryption_key)
# truncate to actual length, as encryption may introduce padding
decrypted_data = AESdecryptCBC(data, key)[:size]
print('== decrypted data:')
print(wrap(decrypted_data))
print()
print('== pretty-printed plist')
pprint.pprint(biplist.readPlistFromString(decrypted_data))
##
# this section is mostly copied from parts of iphone-dataprotection
# http://code.google.com/p/iphone-dataprotection/
CLASSKEY_TAGS = [b"CLAS",b"WRAP",b"WPKY", b"KTYP", b"PBKY"] #UUID
KEYBAG_TYPES = ["System", "Backup", "Escrow", "OTA (icloud)"]
KEY_TYPES = ["AES", "Curve25519"]
PROTECTION_CLASSES={
1:"NSFileProtectionComplete",
2:"NSFileProtectionCompleteUnlessOpen",
3:"NSFileProtectionCompleteUntilFirstUserAuthentication",
4:"NSFileProtectionNone",
5:"NSFileProtectionRecovery?",
6: "kSecAttrAccessibleWhenUnlocked",
7: "kSecAttrAccessibleAfterFirstUnlock",
8: "kSecAttrAccessibleAlways",
9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
11: "kSecAttrAccessibleAlwaysThisDeviceOnly"
}
WRAP_DEVICE = 1
WRAP_PASSCODE = 2
class Keybag(object):
def __init__(self, data):
self.type = None
self.uuid = None
self.wrap = None
self.deviceKey = None
self.attrs = {}
self.classKeys = {}
self.KeyBagKeys = None #DATASIGN blob
self.parseBinaryBlob(data)
def parseBinaryBlob(self, data):
currentClassKey = None
for tag, data in loopTLVBlocks(data):
if len(data) == 4:
data = struct.unpack(">L", data)[0]
if tag == b"TYPE":
self.type = data
if self.type > 3:
print("FAIL: keybag type > 3 : %d" % self.type)
elif tag == b"UUID" and self.uuid is None:
self.uuid = data
elif tag == b"WRAP" and self.wrap is None:
self.wrap = data
elif tag == b"UUID":
if currentClassKey:
self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
currentClassKey = {b"UUID": data}
elif tag in CLASSKEY_TAGS:
currentClassKey[tag] = data
else:
self.attrs[tag] = data
if currentClassKey:
self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
def unlockWithPasscode(self, passcode):
passcode1 = fastpbkdf2.pbkdf2_hmac('sha256', passcode,
self.attrs[b"DPSL"],
self.attrs[b"DPIC"], 32)
passcode_key = fastpbkdf2.pbkdf2_hmac('sha1', passcode1,
self.attrs[b"SALT"],
self.attrs[b"ITER"], 32)
print('== Passcode key')
print(anonymize(hexlify(passcode_key)))
for classkey in self.classKeys.values():
if b"WPKY" not in classkey:
continue
k = classkey[b"WPKY"]
if classkey[b"WRAP"] & WRAP_PASSCODE:
k = AESUnwrap(passcode_key, classkey[b"WPKY"])
if not k:
return False
classkey[b"KEY"] = k
return True
def unwrapKeyForClass(self, protection_class, persistent_key):
ck = self.classKeys[protection_class][b"KEY"]
if len(persistent_key) != 0x28:
raise Exception("Invalid key length")
return AESUnwrap(ck, persistent_key)
def printClassKeys(self):
print("== Keybag")
print("Keybag type: %s keybag (%d)" % (KEYBAG_TYPES[self.type], self.type))
print("Keybag version: %d" % self.attrs[b"VERS"])
print("Keybag UUID: %s" % anonymize(hexlify(self.uuid)))
print("-"*209)
print("".join(["Class".ljust(53),
"WRAP".ljust(5),
"Type".ljust(11),
"Key".ljust(65),
"WPKY".ljust(65),
"Public key"]))
print("-"*208)
for k, ck in self.classKeys.items():
if k == 6:print("")
print("".join(
[PROTECTION_CLASSES.get(k).ljust(53),
str(ck.get(b"WRAP","")).ljust(5),
KEY_TYPES[ck.get(b"KTYP",0)].ljust(11),
anonymize(hexlify(ck.get(b"KEY", b""))).ljust(65),
anonymize(hexlify(ck.get(b"WPKY", b""))).ljust(65),
]))
print()
def loopTLVBlocks(blob):
i = 0
while i + 8 <= len(blob):
tag = blob[i:i+4]
length = struct.unpack(">L",blob[i+4:i+8])[0]
data = blob[i+8:i+8+length]
yield (tag,data)
i += 8 + length
def unpack64bit(s):
return struct.unpack(">Q",s)[0]
def pack64bit(s):
return struct.pack(">Q",s)
def AESUnwrap(kek, wrapped):
C = []
for i in range(len(wrapped)//8):
C.append(unpack64bit(wrapped[i*8:i*8+8]))
n = len(C) - 1
R = [0] * (n+1)
A = C[0]
for i in range(1,n+1):
R[i] = C[i]
for j in reversed(range(0,6)):
for i in reversed(range(1,n+1)):
todec = pack64bit(A ^ (n*j+i))
todec += pack64bit(R[i])
B = Crypto.Cipher.AES.new(kek).decrypt(todec)
A = unpack64bit(B[:8])
R[i] = unpack64bit(B[8:])
if A != 0xa6a6a6a6a6a6a6a6:
return None
res = b"".join(map(pack64bit, R[1:]))
return res
ZEROIV = "\x00"*16
def AESdecryptCBC(data, key, iv=ZEROIV, padding=False):
if len(data) % 16:
print("AESdecryptCBC: data length not /16, truncating")
data = data[0:(len(data)/16) * 16]
data = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv).decrypt(data)
if padding:
return removePadding(16, data)
return data
##
# here are some utility functions, one making sure I don’t leak my
# secret keys when posting the output on Stack Exchange
anon_random = random.Random(0)
memo = {}
def anonymize(s):
if type(s) == str:
s = s.encode('utf-8')
global anon_random, memo
if ANONYMIZE_OUTPUT:
if s in memo:
return memo[s]
possible_alphabets = [
string.digits,
string.digits + 'abcdef',
string.ascii_letters,
"".join(chr(x) for x in range(0, 256)),
]
for a in possible_alphabets:
if all((chr(c) if type(c) == int else c) in a for c in s):
alphabet = a
break
ret = "".join([anon_random.choice(alphabet) for i in range(len(s))])
memo[s] = ret
return ret
else:
return s
def wrap(s, width=78):
"Return a width-wrapped repr(s)-like string without breaking on \’s"
s = repr(s)
quote = s[0]
s = s[1:-1]
ret = []
while len(s):
i = s.rfind('\\', 0, width)
if i <= width - 4: # "\x??" is four characters
i = width
ret.append(s[:i])
s = s[i:]
return '\n'.join("%s%s%s" % (quote, line ,quote) for line in ret)
def readpipe(path):
if stat.S_ISFIFO(os.stat(path).st_mode):
with open(path, 'rb') as pipe:
return pipe.read()
else:
raise Exception("Not a pipe: {!r}".format(path))
if __name__ == '__main__':
main()
Which then prints this output:
Warning: All output keys are FAKE to protect your privacy
== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class WRAP Type Key WPKY Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete 2 AES 4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen 2 AES 09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2 AES e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone 2 AES 902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery? 3 AES a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072
kSecAttrAccessibleWhenUnlocked 2 AES 09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock 2 AES 0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways 2 AES b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly 3 AES 417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 3 AES b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly 3 AES 9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2
== Passcode key
ee34f5bb635830d698074b1e3e268059c590973b0f1138f1954a2a4e1069e612
== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class WRAP Type Key WPKY Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete 2 AES 64e8fc94a7b670b0a9c4a385ff395fe9ba5ee5b0d9f5a5c9f0202ef7fdcb386f 4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen 2 AES 22a218c9c446fbf88f3ccdc2ae95f869c308faaa7b3e4fe17b78cbf2eeaf4ec9 09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2 AES 1004c6ca6e07d2b507809503180edf5efc4a9640227ac0d08baf5918d34b44ef e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone 2 AES 2e809a0cd1a73725a788d5d1657d8fd150b0e360460cb5d105eca9c60c365152 902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery? 3 AES 9a078d710dcd4a1d5f70ea4062822ea3e9f7ea034233e7e290e06cf0d80c19ca a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072
kSecAttrAccessibleWhenUnlocked 2 AES 606e5328816af66736a69dfe5097305cf1e0b06d6eb92569f48e5acac3f294a4 09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock 2 AES 6a4b5292661bac882338d5ebb51fd6de585befb4ef5f8ffda209be8ba3af1b96 0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways 2 AES c0ed717947ce8d1de2dde893b6026e9ee1958771d7a7282dd2116f84312c2dd2 b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly 3 AES 80d8c7be8d5103d437f8519356c3eb7e562c687a5e656cfd747532f71668ff99 417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 3 AES a875a15e3ff901351c5306019e3b30ed123e6c66c949bdaa91fb4b9a69a3811e b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly 3 AES 1e7756695d337e0b06c764734a9ef8148af20dcc7a636ccfea8b2eb96a9e9373 9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2
== decrypted data:
'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD '
'PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist versi'
'on="1.0">\n<dict>\n\t<key>DCIMLastDirectoryNumber</key>\n\t<integer>100</integ'
'er>\n\t<key>DCIMLastFileNumber</key>\n\t<integer>3</integer>\n</dict>\n</plist'
'>\n'
== pretty-printed plist
{'DCIMLastDirectoryNumber': 100, 'DCIMLastFileNumber': 3}
The iphone-dataprotection code posted by Bédrune and Sigwald can decrypt the keychain from a backup, including fun things like saved wifi and website passwords:
$ python iphone-dataprotection/python_scripts/keychain_tool.py ...
--------------------------------------------------------------------------------------
| Passwords |
--------------------------------------------------------------------------------------
|Service |Account |Data |Access group |Protection class|
--------------------------------------------------------------------------------------
|AirPort |Ed’s Coffee Shop |<3FrenchRoast |apple |AfterFirstUnlock|
...
That code no longer works on backups from phones using the latest iOS, but there are some golang ports that have been kept up to date allowing access to the keychain.
<style>
background: url(images/Untitled-2.fw.png);
background-repeat:no-repeat;
background-position:center;
background-size: cover;
</style>
You can use this:
$("#submittername").html(submitter_name);
if the content of foo.py
print __name__
if __name__ == '__main__':
print 'XXXX'
A file foo.py can be used in two ways.
- imported in another file :
import foo
In this case __name__
is foo
, the code section does not get executed and does not print XXXX
.
- executed directly :
python foo.py
When it is executed directly, __name__
is same as __main__
and the code in that section is executed and prints XXXX
One of the use of this functionality to write various kind of unit tests within the same module.
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
Bumped into same warning. If you specified goals and built project using "Run as -> Maven build..." option check and remove pom.xml from Profiles: just below Goals:
The lower the loss, the better a model (unless the model has over-fitted to the training data). The loss is calculated on training and validation and its interperation is how well the model is doing for these two sets. Unlike accuracy, loss is not a percentage. It is a summation of the errors made for each example in training or validation sets.
In the case of neural networks, the loss is usually negative log-likelihood and residual sum of squares for classification and regression respectively. Then naturally, the main objective in a learning model is to reduce (minimize) the loss function's value with respect to the model's parameters by changing the weight vector values through different optimization methods, such as backpropagation in neural networks.
Loss value implies how well or poorly a certain model behaves after each iteration of optimization. Ideally, one would expect the reduction of loss after each, or several, iteration(s).
The accuracy of a model is usually determined after the model parameters are learned and fixed and no learning is taking place. Then the test samples are fed to the model and the number of mistakes (zero-one loss) the model makes are recorded, after comparison to the true targets. Then the percentage of misclassification is calculated.
For example, if the number of test samples is 1000 and model classifies 952 of those correctly, then the model's accuracy is 95.2%.
There are also some subtleties while reducing the loss value. For instance, you may run into the problem of over-fitting in which the model "memorizes" the training examples and becomes kind of ineffective for the test set. Over-fitting also occurs in cases where you do not employ a regularization, you have a very complex model (the number of free parameters W
is large) or the number of data points N
is very low.
You should use bootstarp's variables to control your font-weight if you want a more customized value and/or you're following a scheme that needs to be repeated ; Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks;
you can find all the documentation at http://getbootstrap.com/css.
The slickest method woud be to use LINQ:
var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories)
select file).Count();
The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.
The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.
The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.
Edit: Also worth a look - kashif's comment about json-streamer
and Henrik Heino's comment about bigjson
.
What you probably want is dir()
.
The catch is that classes are able to override the special __dir__
method, which causes dir()
to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__
, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__
or be able to provide a comprehensive list of attributes via __dir__
: many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it.
In the short run, if dir()
isn't sufficient, you could write a function which traverses __dict__
for an object, then __dict__
for all the classes in obj.__class__.__mro__
; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has .feathers
.
algorithm: procedure/formula for solving a problem
How do analyze algorithms and how can we compare algorithms against each other?
example: you and a friend are asked to create a function to sum the numbers from 0 to N. You come up with f(x) and your friend comes up with g(x). Both functions have the same result, but a different algorithm. In order to objectively compare the efficiency of the algorithms we use Big-O notation.
Big-O notation: describes how quickly runtime will grow relative to the input as the input get arbitrarily large.
3 key takeaways:
Space complexity: aside from time complexity, we also care about space complexity (how much memory/space an algorithm uses). Instead of checking the time of operations, we check the size of the allocation of memory.
this fix worked for me:
installed Report Viewer 2008 SP1 Redistributable: http://www.microsoft.com/downloads/details.aspx?familyid=6aaa74bd-a46e-4478-b4e1-2063d18d2d42
took the solution from here: http://blogs.msdn.com/b/brianhartman/archive/2009/10/13/gdi-updated-again.aspx
Happen with me because I ran git config core.autocrlf true
and I forgot to rever back.
After that, when I checkout/pull new code, all LF (break line in Unix) was replaced by CRLF (Break line in Windows).
I ran linter, and all error messages are Expected linebreaks to be 'LF' but found 'CRLF'
To fix the issue, I checked autocrlf
value by running git config --list | grep autocrlf
and I got:
core.autocrlf=true
core.autocrlf=false
I edited the global GIT config ~/.gitconfig
and replaced autocrlf = true
by autocrlf = false
.
After that, I went to my project and do the following (assuming the code in src/
folder):
CURRENT_BRANCH=$(git branch | grep \* | cut -d ' ' -f2);
rm -rf src/*
git checkout $CURRENT_BRANCH src/
I found easiest solution.
@XmlElement(name="attribute")
public String[] getAttributes(){
return attributes.keySet().toArray(new String[1]);
}
}
Now it will generate in you xml output like this:
<attribute>key1<attribute>
...
<attribute>keyN<attribute>
Try this:
runas.exe /savecred /user:administrator "%sysdrive%\testScripts\testscript1.ps1"
It saves the password the first time and never asks again. Maybe when you change the administrator password you will be prompted again.
Use LayoutBuilder
and Get the output you want
Wrap the SingleChildScrollView
with LayoutBuilder
and implement the Builder function.
we can use a LayoutBuilder
to get the box contains
or the amount of space available.
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints){
return SingleChildScrollView(
child: Stack(
children: <Widget>[
Container(
height: constraints.maxHeight,
),
topTitle(context),
middleView(context),
bottomView(context),
],
),
);
}
)
This library works like a charm, easy to integrate and use. https://github.com/dm77/barcodescanner
First of all, it is a waste of an executor slot to wrap the build
step in node
. Your upstream executor will just be sitting idle for no reason.
Second, from a multibranch project, you can use the environment variable BRANCH_NAME
to make logic conditional on the current branch.
Third, the job
parameter takes an absolute or relative job name. If you give a name without any path qualification, that would refer to another job in the same folder, which in the case of a multibranch project would mean another branch of the same repository.
Thus what you meant to write is probably
if (env.BRANCH_NAME == 'master') {
build '../other-repo/master'
}
Edit your php.ini, find allow_url_fopen and set it to allow_url_fopen = 1
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('dddd');
console.log(weekDayName);
mydate is the input date. The variable weekDayName get the name of the day. Here the output is
Wednesday
var mydate = "2017-08-30T00:00:00";_x000D_
console.log(moment(mydate).format('dddd'));_x000D_
console.log(moment(mydate).format('ddd'));_x000D_
console.log('Day in number[0,1,2,3,4,5,6]: '+moment(mydate).format('d'));_x000D_
console.log(moment(mydate).format('MMM'));_x000D_
console.log(moment(mydate).format('MMMM'));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
I found the answer here: http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/
You just concatenate the string and insert a CHAR(13)
where you want your line break.
Example:
DECLARE @text NVARCHAR(100)
SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.'
SELECT @text
This prints out the following:
This is line 1.
This is line 2.