Place an asterisk(*) at the end of the destination path to skip the dispute of D and F.
Example:
xcopy "compressedOutput.xml" "../../Execute Scripts/APIAutomation/Libraries/rerunlastfailedbuild.xml*"
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
Here's a great working example project; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing
Tesseract OCR 3.02.02 API can be confusing, so this guides you through including the Tesseract and Leptonica dll into a Visual Studio C++ Project, and provides a sample file which takes an image path to preprocess and OCR. The preprocessing script in Leptonica converts the input image into black and white book-like text.
Setup
To include this in your own projects, you will need to reference the header files and lib and copy the tessdata folders and dlls.
Copy the tesseract-include folder to the root folder of your project. Now Click on your project in Visual Studio Solution Explorer, and go to Project>Properties.
VC++ Directories>Include Directories:
..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath) C/C++>Preprocessor>Preprocessor Definitions:
_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) C/C++>Linker>Input>Additional Dependencies:
..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies) Now you can include headers in your project's file:
Now copy the two dll files in tesseract-include and the tessdata folder in Debug to the Output Directory of your project.
When you initialize tesseract, you need to specify the location of the parent folder (!important) of the tessdata folder if it is not already the current directory of your executable file. You can copy my script, which assumes tessdata is installed in the executable's folder.
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init("D:\tessdataParentFolder\", ... Sample
You can compile the provided sample, which takes one command line argument of the image path to use. The preprocess() function uses Leptonica to create a black and white book-like copy of the image which makes tesseract work with 90% accuracy. The ocr() function shows the functionality of the Tesseract API to return a string output. The toClipboard() can be used to save text to clipboard on Windows. You can copy these into your own projects.
Upcoming pandas 0.13 version will allow to add rows through loc
on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.
Description is here and this new feature is called Setting With Enlargement.
As other said, the comment in XML are like this
<!-- this is a comment -->
Notice that they can span on multiple lines
<!--
This is a comment
on multiple lines
-->
But they cannot be nested
<!-- This <!-- is a comment --> This is not -->
Also you cannot use them inside tags
<EditText <!--This is not valid--> android:layout_width="fill_parent" />
Got the same error when tried to export a large Excel file (~150.000 rows) Fixed with the following code
Application xlApp = new Application();
xlApp.DefaultSaveFormat = XlFileFormat.xlOpenXMLWorkbook;
Imposing garbage collection is really a low level to high level paradigm shift.
If you look at the way strings are handled in a language with garbage collection, you will find they ONLY allow high level string manipulation functions and do not allow binary access to the strings. Simply put, all string functions first check the pointers to see where the string is, even if you are only drawing out a byte. So if you are doing a loop that processes each byte in a string in a language with garbage collection, it must compute the base location plus offset for each iteration, because it cannot know when the string has moved. Then you have to think about heaps, stacks, threads, etc etc.
I know this thread is old, but this could be another solution:
var do_this = null;
function y(){
// what you wanna do
}
do_this = setInterval(y, 1000);
function y_start(){
do_this = setInterval(y, 1000);
};
function y_stop(){
do_this = clearInterval(do_this);
};
Somewhere in your initialisation put this code.
Array.prototype.contains = function contains(obj) {
for (var i = 0; i < this.length; i++) {
if (this[i] === obj) {
return true;
}
}
return false;
};
Then, you can use it this way:
<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>
Nobody used the STL algorithm/mismatch function yet. If this returns true, prefix is a prefix of 'toCheck':
std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()
Full example prog:
#include <algorithm>
#include <string>
#include <iostream>
int main(int argc, char** argv) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
<< "Will print true if 'prefix' is a prefix of string" << std::endl;
return -1;
}
std::string prefix(argv[1]);
std::string toCheck(argv[2]);
if (prefix.length() > toCheck.length()) {
std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
<< "'prefix' is longer than 'string'" << std::endl;
return 2;
}
if (std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()) {
std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck << '"' << std::endl;
return 0;
} else {
std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"' << toCheck << '"' << std::endl;
return 1;
}
}
Edit:
As @James T. Huggett suggests, std::equal is a better fit for the question: Is A a prefix of B? and is slight shorter code:
std::equal(prefix.begin(), prefix.end(), toCheck.begin())
Full example prog:
#include <algorithm>
#include <string>
#include <iostream>
int main(int argc, char **argv) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
<< "Will print true if 'prefix' is a prefix of string"
<< std::endl;
return -1;
}
std::string prefix(argv[1]);
std::string toCheck(argv[2]);
if (prefix.length() > toCheck.length()) {
std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
<< "'prefix' is longer than 'string'" << std::endl;
return 2;
}
if (std::equal(prefix.begin(), prefix.end(), toCheck.begin())) {
std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck
<< '"' << std::endl;
return 0;
} else {
std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"'
<< toCheck << '"' << std::endl;
return 1;
}
}
In NuGet 3.0 the Get-Package
command is deprecated and replaced with Find-Package
command.
Find-Package Common.Logging -AllVersions
See the NuGet command reference docs for details.
This is the message shown if you try to use Get-Package in Visual Studio 2015.
This Command/Parameter combination has been deprecated and will be removed
in the next release. Please consider using the new command that replaces it:
'Find-Package [-Id] -AllVersions'
Or as @Yishai said, you can use the version number dropdown in the NuGet screen in Visual Studio.
After reading many of the answers, I feel the need to add something:
Strict aliasing (which I'll describe in a bit) is important because:
Memory access can be expensive (performance wise), which is why data is manipulated in CPU registers before being written back to the physical memory.
If data in two different CPU registers will be written to the same memory space, we can't predict which data will "survive" when we code in C.
In assembly, where we code the loading and unloading of CPU registers manually, we will know which data remains intact. But C (thankfully) abstracts this detail away.
Since two pointers can point to the same location in the memory, this could result in complex code that handles possible collisions.
This extra code is slow and hurts performance since it performs extra memory read / write operations which are both slower and (possibly) unnecessary.
The Strict aliasing rule allows us to avoid redundant machine code in cases in which it should be safe to assume that two pointers don't point to the same memory block (see also the restrict
keyword).
The Strict aliasing states it's safe to assume that pointers to different types point to different locations in the memory.
If a compiler notices that two pointers point to different types (for example, an int *
and a float *
), it will assume the memory address is different and it will not protect against memory address collisions, resulting in faster machine code.
For example:
Lets assume the following function:
void merge_two_ints(int *a, int *b) {
*b += *a;
*a += *b;
}
In order to handle the case in which a == b
(both pointers point to the same memory), we need to order and test the way we load data from the memory to the CPU registers, so the code might end up like this:
load a
and b
from memory.
add a
to b
.
save b
and reload a
.
(save from CPU register to the memory and load from the memory to the CPU register).
add b
to a
.
save a
(from the CPU register) to the memory.
Step 3 is very slow because it needs to access the physical memory. However, it's required to protect against instances where a
and b
point to the same memory address.
Strict aliasing would allow us to prevent this by telling the compiler that these memory addresses are distinctly different (which, in this case, will allow even further optimization which can't be performed if the pointers share a memory address).
This can be told to the compiler in two ways, by using different types to point to. i.e.:
void merge_two_numbers(int *a, long *b) {...}
Using the restrict
keyword. i.e.:
void merge_two_ints(int * restrict a, int * restrict b) {...}
Now, by satisfying the Strict Aliasing rule, step 3 can be avoided and the code will run significantly faster.
In fact, by adding the restrict
keyword, the whole function could be optimized to:
load a
and b
from memory.
add a
to b
.
save result both to a
and to b
.
This optimization couldn't have been done before, because of the possible collision (where a
and b
would be tripled instead of doubled).
I modified rushidesai1's answer to include a working example.
import java.io.*;
import java.util.*;
public class JsonMarshaller<T> {
private static ClassLoader loader = JsonMarshaller.class.getClassLoader();
public static void main(String[] args) {
try {
JsonMarshallerUnmarshaller<Station> marshaller = new JsonMarshallerUnmarshaller<>(Station.class);
String jsonString = read(loader.getResourceAsStream("data.json"));
List<Station> stations = marshaller.unmarshal(jsonString);
stations.forEach(System.out::println);
System.out.println(marshaller.marshal(stations));
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("resource")
public static String read(InputStream ios) {
return new Scanner(ios).useDelimiter("\\A").next(); // Read the entire file
}
}
Station [id=123, title=my title, name=my name]
Station [id=456, title=my title 2, name=my name 2]
[{"id":123,"title":"my title","name":"my name"},{"id":456,"title":"my title 2","name":"my name 2"}]
import java.io.*;
import java.util.List;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
public class JsonMarshallerUnmarshaller<T> {
private ObjectMapper mapper;
private Class<T> targetClass;
public JsonMarshallerUnmarshaller(Class<T> targetClass) {
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper = new ObjectMapper();
mapper.getDeserializationConfig().with(introspector);
mapper.getSerializationConfig().with(introspector);
this.targetClass = targetClass;
}
public List<T> unmarshal(String jsonString) throws JsonParseException, JsonMappingException, IOException {
return parseList(jsonString, mapper, targetClass);
}
public String marshal(List<T> list) throws JsonProcessingException {
return mapper.writeValueAsString(list);
}
public static <E> List<E> parseList(String str, ObjectMapper mapper, Class<E> clazz)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(str, listType(mapper, clazz));
}
public static <E> List<E> parseList(InputStream is, ObjectMapper mapper, Class<E> clazz)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(is, listType(mapper, clazz));
}
public static <E> JavaType listType(ObjectMapper mapper, Class<E> clazz) {
return mapper.getTypeFactory().constructCollectionType(List.class, clazz);
}
}
public class Station {
private long id;
private String title;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return String.format("Station [id=%s, title=%s, name=%s]", id, title, name);
}
}
[{
"id": 123,
"title": "my title",
"name": "my name"
}, {
"id": 456,
"title": "my title 2",
"name": "my name 2"
}]
1.question answer-In your mobile having Developer Option in settings and enable that one. after In android studio project source file in bin--> apk file .just copy the apk file and paste in mobile memory in ur pc.. after all finished .you click that apk file in your mobile is automatically installed.
2.question answer-Your mobile is Samsung are just add Samsung Kies software in your pc..its helps to android code run in your mobile ...
It requires a minor CSS addition to make it work with Bootstrap 3:
.input-group-btn:last-child > .form-control {_x000D_
margin-left: -1px;_x000D_
width: auto;_x000D_
}
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="form-group">_x000D_
<div class="input-group">_x000D_
<input class="form-control" name="q" type="text" placeholder="Search">_x000D_
_x000D_
<div class="input-group-btn">_x000D_
<select class="form-control" name="category">_x000D_
<option>select</option>_x000D_
<option>1</option>_x000D_
<option>2</option>_x000D_
<option>3</option>_x000D_
</select>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>
_x000D_
128M == 134217728
, the number you are seeing.
The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.
Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.
Starting with .Net 4.5 you can use Task.Run to simply start an action:
void Foo(string args){}
...
Task.Run(() => Foo("bar"));
int abc= (Math.random()*100);// wrong
you wil get below error message
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to int
int abc= (int) (Math.random()*100);// add "(int)" data type
,known as type casting
if the true result is
int abc= (int) (Math.random()*1)=0.027475
Then you will get output as "0" because it is a integer data type.
int abc= (int) (Math.random()*100)=0.02745
output:2 because (100*0.02745=2.7456...etc)
I know this may not help everyone (who knows, maybe yes), but I had the same problem and after some time, we realized that the cause was something out of the code itself.
The computer trying to reach the server, was in another network, the connection could be established but then dropped.
The way we used to fix it, was to add a static route to the computer, allowing direct access to the server without passing thru the firewall.
route add –p YourServerNetwork mask NetworkMask Router
Sample:
route add –p 172.16.12.0 mask 255.255.255.0 192.168.11.2
I hope it helps someone, it's better to have this, at least as a clue, so if you face it, you know how to solve it.
geonames.org has an api and a data dump of worldwide geographical places.
I came across this question searching for a simular problem. I'm making a webpage with responsive design and the width of elements placed on the page is set to a percent of the screen width. The height is set with a vw value.
Since I'm adding posts with PHP and a database backend, pure CSS was out of the question. I did however find the jQuery/javascript solution a bit troblesome, so I came up with a neat (so I think myself at least) solution.
HTML (or php)
div.imgfill {_x000D_
float: left;_x000D_
position: relative;_x000D_
background-repeat: no-repeat;_x000D_
background-position: 50% 50%;_x000D_
background-size: cover;_x000D_
width: 33.333%;_x000D_
height: 18vw;_x000D_
border: 1px solid black; /*frame of the image*/_x000D_
margin: -1px;_x000D_
}
_x000D_
<div class="imgfill" style="background-image:url(source/image.jpg);">_x000D_
This might be some info_x000D_
</div>_x000D_
<div class="imgfill" style="background-image:url(source/image2.jpg);">_x000D_
This might be some info_x000D_
</div>_x000D_
<div class="imgfill" style="background-image:url(source/image3.jpg);">_x000D_
This might be some info_x000D_
</div>
_x000D_
By using style="" it's posible to have PHP update my page dynamically and the CSS-styling together with style="" will end up in a perfectly covered image, scaled to cover the dynamic div-tag.
The easiest way to reuse the StringBuffer
is to use the method setLength()
public void setLength(int newLength)
You may have the case like
StringBuffer sb = new StringBuffer("HelloWorld");
// after many iterations and manipulations
sb.setLength(0);
// reuse sb
This line is the problem:
int estimatedPopulation (int currentPopulation,
float growthRate (birthRate, deathRate))
Make it:
int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)
instead and invoke the function with three arguments like
estimatePopulation( currentPopulation, birthRate, deathRate );
OR declare it with two arguments like:
int estimatedPopulation (int currentPopulation, float growthrt ) { ... }
and call it as
estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));
Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate
variable in the main()
hides the function with the same name. So within main()
you can only access grouthRate
as float
. On the other hand, outside of the main()
you can only access that name as a function, since that automatic variable is only visible within the scope of main()
.
Just hope I didn't confuse you further :)
For multiple selection dropdown list,cannot accomplish it directly using dropdown..Can be done in similar ways..
Either you have to use checkbox list or listbox (ajax inclusive)
http://www.codeproject.com/Articles/55184/MultiSelect-Dropdown-in-ASP-NET
# file? will only return true for files
File.file?(filename)
and
# Will also return true for directories - watch out!
File.exist?(filename)
I tried differently for the same issue and worked .
Go to your project location in hard drive. ex: /home/user/workspace/project/settings and Delete this file org.eclipse.core.resources.prefs
For full details check out bellow link
http://errorkode.com/viewtopic.php?f=20&t=8&sid=40cff1661bf0ace12878d6d6fb7e75ac
To add to what other suggested I like the following construct to avoid the annoyance of adding members to keyvaluepair collections.
public class KeyValuePairList<Tkey,TValue> : List<KeyValuePair<Tkey,TValue>>{
public void Add(Tkey key, TValue value){
base.Add(new KeyValuePair<Tkey, TValue>(key, value));
}
}
What this means is that the constructor can be initialized with better syntax::
var myList = new KeyValuePairList<int,string>{{1,"one"},{2,"two"},{3,"three"}};
I personally like the above code over the more verbose examples Unfortunately C# does not really support tuple types natively so this little hack works wonders.
If you find yourself really needing more than 2, I suggest creating abstractions against the tuple type.(although Tuple
is a class not a struct like KeyValuePair
this is an interesting distinction).
Curiously enough, the initializer list syntax is available on any IEnumerable
and it allows you to use any Add
method, even those not actually enumerable by your object. It's pretty handy to allow things like adding an object[]
member as a params object[]
member.
Firefox (Win and Mac)
If the Web Dev Toolbar is installed, people can use this keyboard shortcuts: Command + Shift + S (Mac) and Control + Shift + S (Win)
In case you don't want/need to post:
@Html.ActionLink("link caption", "actionName", new { Model.Page }) // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);
[HttpGet]
public ActionResult actionName(int reportID)
{
Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)
Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.
If you choose a language you can't type this Greek may be helpful.
getDisplayLanguage().toString() = English
getLanguage().toString() = en
getISO3Language().toString() = eng
getDisplayLanguage()) = English
getLanguage() = en
getISO3Language() = eng
Now try it with Greek
getDisplayLanguage().toString() = ????????
getLanguage().toString() = el
getISO3Language().toString() = ell
getDisplayLanguage()) = ????????
getLanguage() = el
getISO3Language() = ell
select s.id, s.age, c.count
from students s
inner join (
select age, count(*) as count
from students
group by age
) c on s.age = c.age
order by id
Building upon the answer from David O'Donoghue here is an optimized version of the Delayed Delegate:
using System.Windows.Forms;
using System.Collections.Generic;
using System;
namespace MyTool
{
public class DelayedDelegate
{
static private DelayedDelegate _instance = null;
private Timer _runDelegates = null;
private Dictionary<MethodInvoker, DateTime> _delayedDelegates = new Dictionary<MethodInvoker, DateTime>();
public DelayedDelegate()
{
}
static private DelayedDelegate Instance
{
get
{
if (_instance == null)
{
_instance = new DelayedDelegate();
}
return _instance;
}
}
public static void Add(MethodInvoker pMethod, int pDelay)
{
Instance.AddNewDelegate(pMethod, pDelay * 1000);
}
public static void AddMilliseconds(MethodInvoker pMethod, int pDelay)
{
Instance.AddNewDelegate(pMethod, pDelay);
}
private void AddNewDelegate(MethodInvoker pMethod, int pDelay)
{
if (_runDelegates == null)
{
_runDelegates = new Timer();
_runDelegates.Tick += RunDelegates;
}
else
{
_runDelegates.Stop();
}
_delayedDelegates.Add(pMethod, DateTime.Now + TimeSpan.FromMilliseconds(pDelay));
StartTimer();
}
private void StartTimer()
{
if (_delayedDelegates.Count > 0)
{
int delay = FindSoonestDelay();
if (delay == 0)
{
RunDelegates();
}
else
{
_runDelegates.Interval = delay;
_runDelegates.Start();
}
}
}
private int FindSoonestDelay()
{
int soonest = int.MaxValue;
TimeSpan remaining;
foreach (MethodInvoker invoker in _delayedDelegates.Keys)
{
remaining = _delayedDelegates[invoker] - DateTime.Now;
soonest = Math.Max(0, Math.Min(soonest, (int)remaining.TotalMilliseconds));
}
return soonest;
}
private void RunDelegates(object pSender = null, EventArgs pE = null)
{
try
{
_runDelegates.Stop();
List<MethodInvoker> removeDelegates = new List<MethodInvoker>();
foreach (MethodInvoker method in _delayedDelegates.Keys)
{
if (DateTime.Now >= _delayedDelegates[method])
{
method();
removeDelegates.Add(method);
}
}
foreach (MethodInvoker method in removeDelegates)
{
_delayedDelegates.Remove(method);
}
}
catch (Exception ex)
{
}
finally
{
StartTimer();
}
}
}
}
The class could be slightly more improved by using a unique key for the delegates. Because if you add the same delegate a second time before the first one fired, you might get a problem with the dictionary.
in angular 4 use preserveQueryParams
, ex:
url: /list?page=1
<a [routerLink]="['edit',id]" [preserveQueryParams]="true"></a>
When clicking the link, you are redirected edit/10?page=1
, preserving params
ref: https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array
Allocate memory before using the pointer. If you don't allocate memory *point = 12
is undefined behavior.
int *fun()
{
int *point = malloc(sizeof *point); /* Mandatory. */
*point=12;
return point;
}
Also your printf
is wrong. You need to dereference (*
) the pointer.
printf("%d", *ptr);
^
The getContentResolver()
method is also used when you query a Contact
, using a Cursor
object. I have used getContentResolver()
to query the Android phone Contacts
app, looking for contact info from a person's phone number, to include in my app. The different elements in a query (as shown below) represent what kind of contact details you want, and if they should be ordered, etc. Here is another example.
From the Content Provider Basics page from Android docs.
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
You can use an enumerated value just like an integer:
myChoice c;
...
switch( c ) {
case EASY:
DoStuff();
break;
case MEDIUM:
...
}
When converting SVG to transparent PNG, don't forget to put this BEFORE $imagick->readImageBlob()
:
$imagick->setBackgroundColor(new ImagickPixel('transparent'));
Microsoft windows vista and 7 use NCSI (Network Connectivity Status Indicator) technic:
You should use the background attribute to give an image to that element, and I would use ::after instead of before, this way it should be already drawn on top of your element.
.Modal:before{
content: '';
background:url('blackCarrot.png');
width: /* width of the image */;
height: /* height of the image */;
display: block;
}
Here is what I use since I am not running > 5.2
function getCurrentOrParentDirectory($type='current')
{
if ($type == 'current') {
$path = dirname(__FILE__);
} else {
$path = dirname(dirname(__FILE__));
}
$position = strrpos($path, '/') + 1;
return substr($path, $position);
}
Double dirname with file as suggested by @mike b for the parent directory, and current directory is found by just using that syntax once.
Note this function only returns the NAME, slashes have to be added afterwards.
I have used unique_ptr<char[]>
to implement a preallocated memory pools used in a game engine. The idea is to provide preallocated memory pools used instead of dynamic allocations for returning collision requests results and other stuff like particle physics without having to allocate / free memory at each frame. It's pretty convenient for this kind of scenarios where you need memory pools to allocate objects with limited life time (typically one, 2 or 3 frames) that do not require destruction logic (only memory deallocation).
First make sure you are in markdown edit model in the ipython notebook cell
This is an alternative way to the method proposed by others <img src="myimage.png">
:
![title](img/picture.png)
It also seems to work if the title is missing:
![](img/picture.png)
Note no quotations should be in the path. Not sure if this works for paths with white spaces though!
Unfortunately, ­
's support is so inconsistent between browsers that it can't really be used.
QuirksMode is right -- there's no good way to use soft hyphens in HTML right now. See what you can do to go without them.
2013 edit: According to QuirksMode, ­
now works/is supported on all major browsers.
The easiest way to implement the download is that you direct users to the file location, browsers will do that for you automatically.
You can easily achieve it through:
HttpServletResponse.sendRedirect()
If a <script>
has a src
then the text content of the element will be not be executed as JS (although it will appear in the DOM).
You need to use multiple script elements.
<script>
to load the external scripta <script>
to hold your inline code (with the call to the function in the external script)
Definition:
JOINS are way to query the data that combined together from multiple tables simultaneously.
Concern to RDBMS there are 5-types of joins:
Equi-Join: Combines common records from two tables based on equality condition. Technically, Join made by using equality-operator (=) to compare values of Primary Key of one table and Foreign Key values of another table, hence result set includes common(matched) records from both tables. For implementation see INNER-JOIN.
Natural-Join: It is enhanced version of Equi-Join, in which SELECT operation omits duplicate column. For implementation see INNER-JOIN
Non-Equi-Join: It is reverse of Equi-join where joining condition is uses other than equal operator(=) e.g, !=, <=, >=, >, < or BETWEEN etc. For implementation see INNER-JOIN.
Self-Join:: A customized behavior of join where a table combined with itself; This is typically needed for querying self-referencing tables (or Unary relationship entity). For implementation see INNER-JOINs.
Cartesian Product: It cross combines all records of both tables without any condition. Technically, it returns the result set of a query without WHERE-Clause.
As per SQL concern and advancement, there are 3-types of joins and all RDBMS joins can be achieved using these types of joins.
INNER-JOIN: It merges(or combines) matched rows from two tables. The matching is done based on common columns of tables and their comparing operation. If equality based condition then: EQUI-JOIN performed, otherwise Non-EQUI-Join.
OUTER-JOIN: It merges(or combines) matched rows from two tables and unmatched rows with NULL values. However, can customized selection of un-matched rows e.g, selecting unmatched row from first table or second table by sub-types: LEFT OUTER JOIN and RIGHT OUTER JOIN.
2.1. LEFT Outer JOIN (a.k.a, LEFT-JOIN): Returns matched rows from two tables and unmatched from the LEFT table(i.e, first table) only.
2.2. RIGHT Outer JOIN (a.k.a, RIGHT-JOIN): Returns matched rows from two tables and unmatched from the RIGHT table only.
2.3. FULL OUTER JOIN (a.k.a OUTER JOIN): Returns matched and unmatched from both tables.
CROSS-JOIN: This join does not merges/combines instead it performs Cartesian product.
Note: Self-JOIN can be achieved by either INNER-JOIN, OUTER-JOIN and CROSS-JOIN based on requirement but the table must join with itself.
1.1: INNER-JOIN: Equi-join implementation
SELECT *
FROM Table1 A
INNER JOIN Table2 B ON A.<Primary-Key> =B.<Foreign-Key>;
1.2: INNER-JOIN: Natural-JOIN implementation
Select A.*, B.Col1, B.Col2 --But no B.ForeignKeyColumn in Select
FROM Table1 A
INNER JOIN Table2 B On A.Pk = B.Fk;
1.3: INNER-JOIN with NON-Equi-join implementation
Select *
FROM Table1 A INNER JOIN Table2 B On A.Pk <= B.Fk;
1.4: INNER-JOIN with SELF-JOIN
Select *
FROM Table1 A1 INNER JOIN Table1 A2 On A1.Pk = A2.Fk;
2.1: OUTER JOIN (full outer join)
Select *
FROM Table1 A FULL OUTER JOIN Table2 B On A.Pk = B.Fk;
2.2: LEFT JOIN
Select *
FROM Table1 A LEFT OUTER JOIN Table2 B On A.Pk = B.Fk;
2.3: RIGHT JOIN
Select *
FROM Table1 A RIGHT OUTER JOIN Table2 B On A.Pk = B.Fk;
3.1: CROSS JOIN
Select *
FROM TableA CROSS JOIN TableB;
3.2: CROSS JOIN-Self JOIN
Select *
FROM Table1 A1 CROSS JOIN Table1 A2;
//OR//
Select *
FROM Table1 A1,Table1 A2;
The encoding for the page is not set correctly. Either add a header
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
or use set the appropriate http header.
Content-Type:text/html; charset=UTF-8
Firefox also allows you to change the encoding in View -> Character encoding.
If that's ok, I think javascript should handle UTF8 just fine.
Html.Partial
: returns MvcHtmlString
and slow
Html.RenderPartial
: directly render/write on output stream and returns void
and it's very fast in comparison to Html.Partial
The router can be called in two different ways, depending on whether the navigation occurs on the client or on the server. You have it configured for client-side operation. The key parameter is the second one to the run method, the location.
When you use the React Router Link component, it blocks browser navigation and calls transitionTo to do a client-side navigation. You are using HistoryLocation, so it uses the HTML5 history API to complete the illusion of navigation by simulating the new URL in the address bar. If you're using older browsers, this won't work. You would need to use the HashLocation component.
When you hit refresh, you bypass all of the React and React Router code. The server gets the request for /joblist
and it must return something. On the server you need to pass the path that was requested to the run
method in order for it to render the correct view. You can use the same route map, but you'll probably need a different call to Router.run
. As Charles points out, you can use URL rewriting to handle this. Another option is to use a node.js server to handle all requests and pass the path value as the location argument.
In express, for example, it might look like this:
var app = express();
app.get('*', function (req, res) { // This wildcard method handles all requests
Router.run(routes, req.path, function (Handler, state) {
var element = React.createElement(Handler);
var html = React.renderToString(element);
res.render('main', { content: html });
});
});
Note that the request path is being passed to run
. To do this, you'll need to have a server-side view engine that you can pass the rendered HTML to. There are a number of other considerations using renderToString
and in running React on the server. Once the page is rendered on the server, when your app loads in the client, it will render again, updating the server-side rendered HTML as needed.
str.startswith
allows you to supply a tuple of strings to test for:
if link.lower().startswith(("js", "catalog", "script", "katalog")):
From the docs:
str.startswith(prefix[, start[, end]])
Return
True
if string starts with theprefix
, otherwise returnFalse
.prefix
can also be a tuple of prefixes to look for.
Below is a demonstration:
>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>
I think, the statement
everyone hates it except me
makes any further discussion waste: when you keep using Git, they will blame you if anything goes wrong.
Apart from this, for me Git has two advantages over a centralized VCS that I appreciate most (as partly described by Rob Sobers):
But as I said: I think that you're fighting a lost battle: when everyone hates Git, don't use Git. It could help you more to know why they hate Git instead of trying them to convince them.
If they simply don't want it 'cause it's new to them and are not willing to learn something new: are you sure that you will do successful development with that staff?
Does really every single person hate Git or are they influenced by some opinion leaders? Find the leaders and ask them what's the problem. Convince them and you'll convince the rest of the team.
If you cannot convince the leaders: forget about using Git, take the TFS. Will make your life easier.
Here is how I got without '[' and ']' in C#:
var text = "This is a test string [more or less]";
//Getting only string between '[' and ']'
Regex regex = new Regex(@"\[(.+?)\]");
var matchGroups = regex.Matches(text);
for (int i = 0; i < matchGroups.Count; i++)
{
Console.WriteLine(matchGroups[i].Groups[1]);
}
The output is:
more or less
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”
The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.
# GRANT SELECT ON table_name TO "walters-ro";
That solved the problem.
I guess your elements on the page messes up because you don't clear out your floats, check this out
HTML
<div class="wrap">
<div class="floatleft"></div>
<div class="floatright"></div>
<div style="clear: both;"></div>
</div>
CSS
.wrap {
width: 100%;
}
.floatleft {
float:left;
width: 80%;
background-color: #ff0000;
height: 400px;
}
.floatright {
float: right;
background-color: #00ff00;
height: 400px;
width: 20%;
}
In addition to @thoughtrepo's answer:
Until we do not have definitely typed events in React it might be useful to have a special target interface for input controls:
export interface FormControlEventTarget extends EventTarget{
value: string;
}
And then in your code cast to this type where is appropriate to have IntelliSense support:
import {FormControlEventTarget} from "your.helper.library"
(event.target as FormControlEventTarget).value;
You were almost there : just add theme(legend.title=element_blank())
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
theme(legend.title=element_blank())
This page on Cookbook for R gives plenty of details on how to customize legends.
I found this question due the exception mentioned in it. My Web.Config didn't have any <roleManager>
tag. I realized that even if I added it (as Infotekka suggested), it ended up in a Database exception. After following the suggestions in the other answers in here, none fully solved the problem.
Since these Web.Config tags can be automatically generated, it felt wrong to solve it by manually adding them. If you are in a similar case, undo all the changes you made to Web.Config and in Visual Studio:
Check your Web.config and now you should have at least one <providers>
tag inside Profile, Membership, SessionState tags and also inside the new RoleManager tag, like this:
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=NUMBER" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
Add enabled="true"
like so:
<roleManager defaultProvider="DefaultRoleProvider" enabled="true">
Press F6 to Build and now it should be OK to proceed to a database update without having that exception:
update-database -verbose
and the Seed method will run just fine (if you haven't messed elsewhere) and create a few tables in your Database;You can do this with psutil which is cross-platform:
import psutil
nics = psutil.net_if_addrs()
print [j.address for j in nics[i] for i in nics if i!="lo" and j.family==17]
Try this:
schtasks /change /ENABLE /tn "Auto Restart" /s mycomutername /u mycomputername\username/p mypassowrd
$duplicate = false;
if(count(array) != count(array_unique(array))){
$duplicate = true;
}
Try this steps:
You need to allow Allow USB debugging in your device when popup.
If your text contains only one individual:
import re
# creation
with open('pers.txt','wb') as g:
g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 ')
with open('pers.txt','rb') as h:
print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt before treatment:\n',h.read()
# treatment
def roplo(file_name,what):
patR = re.compile('^([^\r\n]+[\r\n]+)[^\r\n]+')
with open(file_name,'rb+') as f:
ch = f.read()
f.seek(0)
f.write(patR.sub('\\1'+what,ch))
roplo('pers.txt','Mage')
# after treatment
with open('pers.txt','rb') as h:
print '\nexact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt after treatment:\n',h.read()
If your text contains several individuals:
import re
# creation
with open('pers.txt','wb') as g:
g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 \n Jim \n dragonfly\r300\r2\n10\r\nSomo\ncosmonaut\n490\r\n3\r65')
with open('pers.txt','rb') as h:
print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt before treatment:\n',h.read()
# treatment
def ripli(file_name,who,what):
with open(file_name,'rb+') as f:
ch = f.read()
x,y = re.search('^\s*'+who+'\s*[\r\n]+([^\r\n]+)',ch,re.MULTILINE).span(1)
f.seek(x)
f.write(what+ch[y:])
ripli('pers.txt','Jim','Wizard')
# after treatment
with open('pers.txt','rb') as h:
print 'exact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt after treatment:\n',h.read()
If the “job“ of an individual was of a constant length in the texte, you could change only the portion of texte corresponding to the “job“ the desired individual: that’s the same idea as senderle’s one.
But according to me, better would be to put the characteristics of individuals in a dictionnary recorded in file with cPickle:
from cPickle import dump, load
with open('cards','wb') as f:
dump({'Dan':['Warrior',500,1,0],'Jim':['dragonfly',300,2,10],'Somo':['cosmonaut',490,3,65]},f)
with open('cards','rb') as g:
id_cards = load(g)
print 'id_cards before change==',id_cards
id_cards['Jim'][0] = 'Wizard'
with open('cards','w') as h:
dump(id_cards,h)
with open('cards') as e:
id_cards = load(e)
print '\nid_cards after change==',id_cards
Create a lookup table that computes font-size based on the length of the string inside your <div>
.
const fontSizeLookupTable = () => {
// lookup table looks like: [ '72px', ..., '32px', ..., '16px', ..., ]
let a = [];
// adjust this based on how many characters you expect in your <div>
a.length = 32;
// adjust the following ranges empirically
a.fill( '72px' , );
a.fill( '32px' , 4 , );
a.fill( '16px' , 8 , );
// add more ranges as necessary
return a;
}
const computeFontSize = stringLength => {
const table = fontSizeLookupTable();
return stringLength < table.length ? table[stringLength] : '16px';
}
Adjust and tune all parameters by empirical test.
The main difference between logging in with a postgres user or any other user created by us, is that when using the postgres user it is NOT necessary to specify the host with -h and instead for another user if.
$ psql -U postgres
# CREATE ROLE usertest LOGIN PASSWORD 'pwtest';
# CREATE DATABASE dbtest WITH OWNER = usertest;
# SHOW port;
# \q
$ psql -h localhost -d dbtest -U usertest -p 5432
GL
Actually I fixed this issue in a very simple way
home path
, like /root
.fonts
all your font files
to .fonts
, you can copy the font from C:\windows\fonts
if you use windows.sudo apt-get install fontconfig
fc-cache –fv
to rebuid fonts caches.using(var writer = new StringWriter()) {
results.WriteXml(writer);
Console.WriteLine(writer.ToString());
}
Of course the usefulness of this depends on how important the formatting is. If it's just a debug dump, I find XML outputs like this very readable. However, if the formatting is important to you, then you have no choice but to write your own method to do it.
You can't subtract a list from a list.
>>> [3, 7] - [1, 2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
Simple way to do it is using numpy
:
>>> import numpy as np
>>> np.array([3, 7]) - np.array([1, 2])
array([2, 5])
You can also use list comprehension, but it will require changing code in the function:
>>> [a - b for a, b in zip([3, 7], [1, 2])]
[2, 5]
>>> import numpy as np
>>>
>>> def Naive_Gauss(Array,b):
... n = len(Array)
... for column in xrange(n-1):
... for row in xrange(column+1, n):
... xmult = Array[row][column] / Array[column][column]
... Array[row][column] = xmult
... #print Array[row][col]
... for col in xrange(0, n):
... Array[row][col] = Array[row][col] - xmult*Array[column][col]
... b[row] = b[row]-xmult*b[column]
... print Array
... print b
... return Array, b # <--- Without this, the function will return `None`.
...
>>> print Naive_Gauss(np.array([[2,3],[4,5]]),
... np.array([[6],[7]]))
[[ 2 3]
[-2 -1]]
[[ 6]
[-5]]
(array([[ 2, 3],
[-2, -1]]), array([[ 6],
[-5]]))
I hope you've installed -
npm install --save-dev @types/jasmine
Then put following import at the top of the hero.spec.ts
file -
import 'jasmine';
It should solve the problem.
i agree with you about alternative solutions which you mentioned above
1. Use POST instead of GET;
2. Transform the List into a JSON string and pass it to the service.
and its true that you can't add List
to MultiValuedMap
because of its impl class MultivaluedMapImpl
have capability to accept String Key and String Value. which is shown in following figure
still you want to do that things than try following code.
Controller Class
package net.yogesh.test;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import com.google.gson.Gson;
@Path("test")
public class TestController {
@Path("testMethod")
@GET
@Produces("application/text")
public String save(
@QueryParam("list") List<String> list) {
return new Gson().toJson(list) ;
}
}
Client Class
package net.yogesh.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class Client {
public static void main(String[] args) {
String op = doGet("http://localhost:8080/JerseyTest/rest/test/testMethod");
System.out.println(op);
}
private static String doGet(String url){
List<String> list = new ArrayList<String>();
list = Arrays.asList(new String[]{"string1,string2,string3"});
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
String lst = (list.toString()).substring(1, list.toString().length()-1);
params.add("list", lst);
ClientConfig config = new DefaultClientConfig();
com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
WebResource resource = client.resource(url);
ClientResponse response = resource.queryParams(params).type("application/x-www-form-urlencoded").get(ClientResponse.class);
String en = response.getEntity(String.class);
return en;
}
}
hope this'll help you.
Swift 4 .
Simplest Method
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight : Int = Int(keyboardSize.height)
print("keyboardHeight",keyboardHeight)
}
}
If you merged the branch, then reverted the merge using a pull request and merged that pull request to revert.
The easiest way I felt was to:
git revert -m 1 xxxxxx
(if the revert was merged using a branch) or using git revert xxxxxx
if it was a simple reverttry this:
public class SomAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private CallBack callBack;
public interface CallBack {
void async( JSONObject jsonResult );
void sync( JSONObject jsonResult );
void progress( Integer... status );
void cancel();
}
public SomAsyncTask(CallBack callBack) {
this.callBack = callBack;
}
@Override
protected JSONObject doInBackground(String... strings) {
JSONObject dataJson = null;
//TODO query, get some dataJson
if(this.callBack != null)
this.callBack.async( dataJson );// asynchronize with MAIN LOOP THREAD
return dataJson;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if(this.callBack != null)
this.callBack.progress(values);// synchronize with MAIN LOOP THREAD
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if(this.callBack != null)
this.callBack.sync(jsonObject);// synchronize with MAIN LOOP THREAD
}
@Override
protected void onCancelled() {
super.onCancelled();
if(this.callBack != null)
this.callBack.cancel();
}
}
And usage example:
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context _localContext = getContext();
SomeAsyncTask.CallBack someCallBack = new SomeAsyncTask.CallBack() {
@Override
public void async(JSONObject jsonResult) {//async thread
//some async process, e.g. send data to server...
}
@Override
public void sync(JSONObject jsonResult) {//sync thread
//get result...
//get some resource of Activity variable...
Resources resources = _localContext.getResources();
}
@Override
public void progress(Integer... status) {//sync thread
//e.g. change status progress bar...
}
@Override
public void cancel() {
}
};
new SomeAsyncTask( someCallBack )
.execute("someParams0", "someParams1", "someParams2");
}
Bottom right hand corner on the status bar, click Spaces: N
(or Tab Width: N
, where N is an integer), ensure it says Tab Width: 4
for converting from four spaces, and then select Convert Indentation to Tabs
from the contextual menu that will appear from the initial click.
Similarly, if you want to do the opposite, click the Spaces
or Tab Width
text on the status bar and select from the same menu.
pip install --user package-name
Seems to work, but the package is install the the path of user. such as :
"c:\users\***\appdata\local\temp\pip-req-tracker-_akmzo\42a6c7d627641b148564ff35597ec30fd5543aa1cf6e41118b98d7a3"
I want to install the package in python folder such c:\Python27. I install the module into the expected folder by:
pip install package-name --no-cache-dir
You can use
insert into <table_name> select <fieldlist> from <tables>
Using Thomas Bratt's answer above, just make sure your build.xml is configured properly :
<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file -->
<project name="TestMain" default="CreateJar">
<target name="CreateJar" description="Create Jar file">
<jar jarfile="Test.jar" basedir="bin/" includes="**/*.class" />
</target>
</project>
(Notice the double asterisk - it will tell build to look for .class files in all sub-directories.)
If you want to assign a long str to variable, you can do it as below:
net_weights_pathname = (
'/home/acgtyrant/BigDatas/'
'model_configs/lenet_iter_10000.caffemodel')
Do not add any comma, or you will get a tuple which contains many strs!
A little late to the party, but if you are looking for a solution like Yury's the following code will help you identify if the issue is related to a self-sign certificate and, if so ignore the self-sign error. You could obviously check for other SSL errors if you so desired.
The code we use (courtesy of Microsoft - http://msdn.microsoft.com/en-us/library/office/dd633677(v=exchg.80).aspx) is as follows:
private static bool CertificateValidationCallBack(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
{
return true;
}
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
{
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else
{
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
}
}
}
}
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
return true;
}
else
{
// In all other cases, return false.
return false;
}
}
Instants are already in UTC and already have a default date format of yyyy-MM-dd. If you're happy with that and don't want to mess with time zones or formatting, you could also toString()
it:
Instant instant = Instant.now();
instant.toString()
output: 2020-02-06T18:01:55.648475Z
Don't want the T and Z? (Z indicates this date is UTC. Z stands for "Zulu" aka "Zero hour offset" aka UTC):
instant.toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.663763
Want milliseconds instead of nanoseconds? (So you can plop it into a sql query):
instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.664
etc.
Put this method in your BaseController:
@SuppressWarnings("ConstantConditions")
protected String fetchClientIpAddr() {
HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
String ip = Optional.ofNullable(request.getHeader("X-FORWARDED-FOR")).orElse(request.getRemoteAddr());
if (ip.equals("0:0:0:0:0:0:0:1")) ip = "127.0.0.1";
Assert.isTrue(ip.chars().filter($ -> $ == '.').count() == 3, "Illegal IP: " + ip);
return ip;
}
open()
is a low-level os call. fdopen()
converts an os-level file descriptor to the higher-level FILE-abstraction of the C language. fopen()
calls open()
in the background and gives you a FILE-pointer directly.
There are several advantages to using FILE-objects rather raw file descriptors, which includes greater ease of usage but also other technical advantages such as built-in buffering. Especially the buffering generally results in a sizeable performance advantage.
As an alternative, there's a nice 3rd party library designed just for this use case. Whereby you need to generate headers based on the data being stored in the adapter. They are called Rolodex adapters and are used with ExpandableListViews
. They can easily be customized to behave like a normal list with headers.
Using the OP's Event
objects and knowing the headers are based on the Date
associated with it...the code would look something like this:
The Activity
//There's no need to pre-compute what the headers are. Just pass in your List of objects.
EventDateAdapter adapter = new EventDateAdapter(this, mEvents);
mExpandableListView.setAdapter(adapter);
The Adapter
private class EventDateAdapter extends NFRolodexArrayAdapter<Date, Event> {
public EventDateAdapter(Context activity, Collection<Event> items) {
super(activity, items);
}
@Override
public Date createGroupFor(Event childItem) {
//This is how the adapter determines what the headers are and what child items belong to it
return (Date) childItem.getDate().clone();
}
@Override
public View getChildView(LayoutInflater inflater, int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
//Inflate your view
//Gets the Event data for this view
Event event = getChild(groupPosition, childPosition);
//Fill view with event data
}
@Override
public View getGroupView(LayoutInflater inflater, int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
//Inflate your header view
//Gets the Date for this view
Date date = getGroup(groupPosition);
//Fill view with date data
}
@Override
public boolean hasAutoExpandingGroups() {
//This forces our group views (headers) to always render expanded.
//Even attempting to programmatically collapse a group will not work.
return true;
}
@Override
public boolean isGroupSelectable(int groupPosition) {
//This prevents a user from seeing any touch feedback when a group (header) is clicked.
return false;
}
}
use the "maxlength" attribute as others have said.
if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: How to impose maxlength on textArea in HTML using JavaScript
To do as the answer above, you can override the onAttach
method of fragment:
public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
DBHelper = new DatabaseHelper(activity);
}
}
Suppose a = 2
and b = 3
THEN, a ||= b
will be resulted to a
's value i.e. 2
.
As when a evaluates to some value not resulted to false
or nil
.. That's why it ll
not evaluate b
's value.
Now Suppose a = nil
and b = 3
.
Then a ||= b
will be resulted to 3
i.e. b
's value.
As it first try to evaluates a's value which resulted to nil
.. so it evaluated b
's value.
The best example used in ror app is :
#To get currently logged in iser
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
# Make current_user available in templates as a helper
helper_method :current_user
Where, User.find_by_id(session[:user_id])
is fired if and only if @current_user
is not initialized before.
just import requests
and use from json() method :
source = requests.get("url").json()
print(source)
OR you can use this :
import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)
In the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later. [...]
The opposite operation, extracting a data structure from a series of bytes, is deserialization. From Wikipedia
In Python "serialization" does nothing else than just converting the given data structure (e.g. a dict
) into its valid JSON pendant (object).
True
will be converted to JSONs true
and the dictionary itself will then be encapsulated in quotes.True
/ False
, true
/ false
json
is the standard way to do serialization:Code example:
data = {
"president": {
"name": "Zaphod Beeblebrox",
"species": "Betelgeusian",
"male": True,
}
}
import json
json_data = json.dumps(data, indent=2) # serialize
restored_data = json.loads(json_data) # deserialize
# serialized json_data now looks like:
# {
# "president": {
# "name": "Zaphod Beeblebrox",
# "species": "Betelgeusian",
# "male": true
# }
# }
Source: realpython.com
I had a similar problem, but I was getting an error message
cannot execute binary file
I discovered that the filename contained non-ASCII characters. When those were fixed, the script ran fine with ./script.sh
.
You should have a look on the -regextype
argument of find
, see manpage:
-regextype type
Changes the regular expression syntax understood by -regex and -iregex
tests which occur later on the command line. Currently-implemented
types are emacs (this is the default), posix-awk, posix-basic,
posix-egrep and posix-extended.
I guess the emacs
type doesn't support the [[:digit:]]
construct. I tried it with posix-extended
and it worked as expected:
find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'
You will need to assign an ID to the checkbox:
<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">
and then in JavaScript:
document.getElementById("checkboxId").checked = false;
"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."
I prefer /^\s+$|^$/gi
to match empty and empty spaces.
console.log(" ".match(/^\s+$|^$/gi));_x000D_
console.log("".match(/^\s+$|^$/gi));
_x000D_
In Kotlin, if you want to create the local constants which are supposed to be used with in the class then you can create it like below
val MY_CONSTANT = "Constants"
And if you want to create a public constant in kotlin like public static final in java, you can create it as follow.
companion object{
const val MY_CONSTANT = "Constants"
}
A formula to return either the first word or all the other words.
=IF(ISERROR(FIND(" ",TRIM(A2),1)),TRIM(A2),MID(TRIM(A2),FIND(" ",TRIM(A2),1),LEN(A2)))
Examples and results
Text Description Results
Blank
Space
some Text no space some
some text Text with space text
some Text with leading space some
some Text with trailing space some
some text some text Text with multiple spaces text some text
Comments on Formula:
If you don't want to install xDebug or other extensions and just want to run a PHP file without debugging, you can accomplish this using build tasks.
First open the command palette (Ctrl+Shift+P in Windows, ?+Shift+P in Mac), and select "Tasks:Open User Tasks". Now copy my configuration below into your tasks.json file. This creates user-level tasks which can be used any time and in any workspace.
{
"version": "2.0.0",
"tasks": [
{
"label": "Start Server",
"type": "shell",
"command": "php -S localhost:8080 -t ${fileDirname}",
"isBackground": true,
"group": "build",
"problemMatcher": []
},
{
"label": "Run In Browser",
"type": "shell",
"command": "open http://localhost:8080/${fileBasename}",
"windows": {
"command": "explorer 'http://localhost:8080/${fileBasename}'"
},
"group": "build",
"problemMatcher": []
}
{
"label": "Run In Terminal",
"type": "shell",
"command": "php ${file}",
"group": "none",
"problemMatcher": []
}
]
}
If you want to run your php file in the terminal, open the command palette and select "Tasks: Run Task" followed by "Run In Terminal".
If you want to run your code on a webserver which serves a response to a web browser, open the command palette and select "Tasks: Run Task" followed by "Start Server" to run PHP's built-in server, then "Run In Browser" to run the currently open file from your browser.
Note that if you already have a webserver running, you can remove the Start Server
task and update the localhost:8080
part to point to whatever URL you are using.
Note: This section was in my original answer. I originally thought that it works without PHP Debug but it looks like PHP Debug actually exposes the php
type in the launch configuration. There is no reason to use it over the build task method described above. I'm keeping it here in case it is useful.
Copy the following configuration into your user settings:
{
"launch": {
"version": "0.2.0",
"configurations": [
{
"type": "php",
"request": "launch",
"name": "Run using PHP executable",
"program": "${file}",
"runtimeExecutable": "/usr/bin/php"
},
]
},
// all your other user settings...
}
This creates a global launch configuration that you can use on any PHP file. Note the runtimeExecutable
option. You will need to update this with the path to the PHP executable on your machine. After you copy the configuration above, whenever you have a PHP file open, you can press the F5 key to run the PHP code and have the output displayed in the vscode terminal.
You will find the tomcat-users.xml in \Users\<Name>\AppData\Roaming\Netbeans\
. It exists at least twice on your machine, depending on the number of Tomcat installations you have.
Edit 2018-10-11: It looks like there is a good chance the standard described below may not go through, consider pipelineing as an alternative (does not behave exactly the same but methods could be implemented in a similar manor).
This is exactly why I am excited about es7, in future you will be able to do something like the code below (some of the specs are not complete so use with caution, I will try to keep this up to date). But basically using the new :: bind operator, you will be able to run a method on an object as if the object's prototype contains the method. eg [Object]::[Method] where normally you would call [Object].[ObjectsMethod]
Note to do this today (24-July-16) and have it work in all browsers you will need to transpile your code for the following functionality:Import / Export, Arrow functions, Promises, Async / Await and most importantly function bind. The code below could be modfied to use only function bind if nessesary, all this functionality is neatly available today by using babel.
YourCode.js (where 'lots of work to do' must simply return a promise, resolving it when the asynchronous work is done.)
import { asyncForEach } from './ArrayExtensions.js';
await [many many elements]::asyncForEach(() => lots of work to do);
ArrayExtensions.js
export function asyncForEach(callback)
{
return Promise.resolve(this).then(async (ar) =>
{
for(let i=0;i<ar.length;i++)
{
await callback.call(ar, ar[i], i, ar);
}
});
};
export function asyncMap(callback)
{
return Promise.resolve(this).then(async (ar) =>
{
const out = [];
for(let i=0;i<ar.length;i++)
{
out[i] = await callback.call(ar, ar[i], i, ar);
}
return out;
});
};
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
Made it.
from datetime import datetime
dateNow = datetime.now().strftime('%Y%m%d')
The accepted answer by Aristotle will show all reachable commits, including non-stash-like commits. To filter out the noise:
git fsck --no-reflog | \
awk '/dangling commit/ {print $3}' | \
xargs git log --no-walk --format="%H" \
--grep="WIP on" --min-parents=3 --max-parents=3
This will only include commits which have exactly 3 parent commits (which a stash will have), and whose message includes "WIP on".
Keep in mind, that if you saved your stash with a message (e.g. git stash save "My newly created stash"
), this will override the default "WIP on..." message.
You can display more information about each commit, e.g. display the commit message, or pass it to git stash show
:
git fsck --no-reflog | \
awk '/dangling commit/ {print $3}' | \
xargs git log --no-walk --format="%H" \
--grep="WIP on" --min-parents=3 --max-parents=3 | \
xargs -n1 -I '{}' bash -c "\
git log -1 --format=medium --color=always '{}'; echo; \
git stash show --color=always '{}'; echo; echo" | \
less -R
if you are trying to use jquery in your electron app before adding jquery you should add it to your modules:
<script>
if (typeof module === 'object') {
window.module = module;
module = undefined;
}
</script>
<script src="js/jquery-3.5.1.min.js"></script>
The command fails because it has space in one of the folder name, i.e. 'VirtualBox VMs.
VBoxManage internalcommands sethduuid /home/user/VirtualBox VMs/drupal/drupal.vhd
If there is no space at folder name or file name, then the command will work even without quoting it, e.g. after changing 'VirtualBox VMs' into 'VBoxVMs'
VBoxManage internalcommands sethduuid /home/user/VBoxVMs/drupal/drupal.vhd
My answer from here:
Just reiterating the right solution:
namespace mySpace
{
public static class Util
{
private static rnd = new Random();
public static int GetRandom()
{
return rnd.Next();
}
}
}
So you can call:
var i = Util.GetRandom();
all throughout.
If you strictly need a true stateless static method to generate random numbers, you can rely on a Guid
.
public static class Util
{
public static int GetRandom()
{
return Guid.NewGuid().GetHashCode();
}
}
It's going to be a wee bit slower, but can be much more random than Random.Next
, at least from my experience.
But not:
new Random(Guid.NewGuid().GetHashCode()).Next();
The unnecessary object creation is going to make it slower especially under a loop.
And never:
new Random().Next();
Not only it's slower (inside a loop), its randomness is... well not really good according to me..
Yes It's Possible.
UITableView
has a delegate method didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[UIView animateWithDuration:.6
delay:0
usingSpringWithDamping:UIViewAnimationOptionBeginFromCurrentState
initialSpringVelocity:0
options:UIViewAnimationOptionBeginFromCurrentState animations:^{
cellindex = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
NSArray* indexArray = [NSArray arrayWithObjects:indexPath, nil];
[violatedTableView beginUpdates];
[violatedTableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
[violatedTableView endUpdates];
}
completion:^(BOOL finished) {
}];
}
But in your case if the user scrolls and selects a different cell then u need to have the last selected cell to shrink and expand the currently selected cell reloadRowsAtIndexPaths:
calls heightForRowAtIndexPath:
so handle accordingly.
Only if you are targeting webkit-based browsers (Chrome and Safari, maybe you are developing a Chrome WebApp, who knows...), you can use the following:
input[type='radio'] {
-webkit-appearance: none;
}
And then style it as if it were a simple HTML element, for example applying a background image.
Use input[type='radio']:active
for when the input is selected, to provide the alternate graphics
Update: As of 2018 you can add the following to support multiple browser vendors:
input[type="radio"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
Posting another script solution DateX (author) for anyone interested
DateX does NOT wrap the original Date
object, but instead offers an identical interface with additional methods to format, localise, parse, diff and validate dates easily. So one can just do new DateX(..)
instead of new Date(..)
or use the lib as date utilities or even as wrapper or replacement around Date
class.
The date format used is identical to php date format.
c-like format is also supported (although not fully)
for the example posted (YYYY/mm/dd hh:m:sec
) the format to use would be Y/m/d H:i:s
eg
var formatted_date = new DateX().format('Y/m/d H:i:s');
or
var formatted_now_date_gmt = new DateX(DateX.UTC()).format('Y/m/d H:i:s');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC
Here's a Kotlin Extension Function I have for this
fun TextView.setColouredSpan(word: String, color: Int) {
val spannableString = SpannableString(text)
val start = text.indexOf(word)
val end = text.indexOf(word) + word.length
try {
spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text = spannableString
} catch (e: IndexOutOfBoundsException) {
println("'$word' was not not found in TextView text")
}
}
Use it after you have set your text to the TextView like so
private val blueberry by lazy { getColor(R.color.blueberry) }
textViewTip.setColouredSpan("Warning", blueberry)
I have build such kind of application using approximatively the same approach except :
UIImage
but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.Whenever the user start zooming, I acquire the CGPDFPage
and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context
is like :
CGAffineTransform currentCTM = CGContextGetCTM(context);
if (currentCTM.a == 1.0 && baseImage) {
//Calculate ideal scale
CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height;
CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);
CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
@synchronized(issue) {
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
CGContextConcatCTM(context, pdfToPageTransform);
CGContextDrawPDFPage(context, pdfPage);
}
}
issue is the object containg the CGPDFDocumentRef
. I synchronize the part where I access the pdfDoc
property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef
object do some internal caching that I did not find how to get rid of.
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
am assuming that you want to know how to format numbers in SSRS
Just right click
the TextBox
on which you want to apply formatting, go to its expression
.
suppose its expression is something like below
=Fields!myField.Value
then do this
=Format(Fields!myField.Value,"##.##")
or
=Format(Fields!myFields.Value,"00.00")
difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00
this should give you an idea.
also: you might have to convert your field into a numerical one. i.e.
=Format(CDbl(Fields!myFields.Value),"00.00")
so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:
UPDATE :
if you want to apply variable formatting on the same column based on row values i.e.
you want myField
to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)
Go to the appropriate textbox and go to its expression and do this:
=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0,
Format(Fields!myField.Value, "##.##"),Fields!myField.Value)
so basically you are using IIF(condition, true,false)
operator of SSRS,
ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.
this should give you an idea, how to handle variable formatting.
In the link you provided, thats not a loop in sql...
thats a loop in programming language
they are first getting list of all distinct districts, and then for each district executing query again.
The code below works. Note the use of countDocuments.
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/myApp');
var userSchema = new mongoose.Schema({name:String,password:String});
var userModel =db.model('userlists',userSchema);
var anand = new userModel({ name: 'anand', password: 'abcd'});
anand.save(function (err, docs) {
if (err) {
console.log('Error');
} else {
userModel.countDocuments({name: 'anand'}, function(err, c) {
console.log('Count is ' + c);
});
}
});
OK, first of all I'm not sure how it works when you create a div using (document.createElement('div'))
, so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?
If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?
Here's the code for my example:
HTML
<a href="#new">Click</a>
<div id="new">
Fade in ...
</div>
CSS
#new {
width: 100px;
height: 100px;
border: 1px solid #000000;
opacity: 0;
}
#new:target {
-webkit-transition: opacity 2.0s ease-in;
-moz-transition: opacity 2.0s ease-in;
-o-transition: opacity 2.0s ease-in;
opacity: 1;
}
... and here's a jsFiddle
The "play" button is specifically for build and run (or test or profile, etc). The Archive action is intended to build for release and to generate an archive that is suitable for submission to the app store. If you want to skip that, you can choose Product > Build For > Archive to force the release build without actually archiving. To find the built product, expand the Products group in the Project navigator, right-click the product and choose to show in Finder.
That said, you can click and hold the play button for a menu of other build actions (including Build and Archive).
Cross-site cookies are allowed if:
Set-Cookie
response header includes SameSite=None; Secure
as seen here and hereLet's clarify a "domain" vs a "site"; I always find a quick reminder of "anatomy of a URL" helps me. In this URL https://example.com:8888/examples/index.html
, remember these main parts (got from this paper):
https://
example.com
8888
/examples/index.html
.Notice the difference between "path" and "site" for Cookie purposes. "path" is not security-related; "site" is security-related:
path
Servers can set a Path
attribute in the Set-Cookie
, but it doesn't seem security related:
Note that
path
was intended for performance, not security. Web pages having the same origin still can access cookie viadocument.cookie
even though the paths are mismatched.
site
The SameSite attribute, according to web.dev article, can restrict or allow cross-site cookies; but what is a "site"?
It's helpful to understand exactly what 'site' means here. The site is the combination of the domain suffix and the part of the domain just before it. For example, the
www.web.dev
domain is part of theweb.dev
site.
This means what's to the left of web.dev
is a subdomain; yep, www
is the subdomain (but the subdomain is a part of the host; see the BONUS reply in this answer)
In this URL https://www.example.com:8888/examples/index.html
, remember these parts:
https://
example.com
8888
www.example.com
example.com
www
/examples/index.html
Useful links:
(Be careful; I was testing my feature in Chrome Incognito tab; according to my chrome://settings/cookies
; my settings were "Block third party cookies in Incognito", so I can't test Cross-site cookies in Incognito.)
if exist yourfilename (
echo Yes
) else (
echo No
)
Replace yourfilename with the name of your file.
if exist yourfoldername\ (
echo Yes
) else (
echo No
)
Replace yourfoldername with the name of your folder.
A trailing backslash (\
) seems to be enough to distinguish between directories and ordinary files.
After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,
client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);
You can try the following:
from haversine import haversine
haversine((45.7597, 4.8422),(48.8567, 2.3508), unit='mi')
243.71209416020253
Using Guava's Ints.asList()
it is as simple as:
Collections.shuffle(Ints.asList(array));
just add
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
<scope>runtime</scope>
</dependency>
Instead of faking a Boolean and leaving a trap for future readers, why not just use a better value than true and false?
For example:
build_state=success
if something-horrible; then
build_state=failed
fi
if [[ "$build_state" == success ]]; then
echo go home; you are done
else
echo your head is on fire; run around in circles
fi
For example, my
vector<int> foo
contains (5,2,6,87,251). A function takesvector<int>*
and I want to pass it a pointer to (2,6,87,251).
A pointer to a vector<int>
is not at all the same thing as a pointer to the elements of the vector.
In order to do this you will need to create a new vector<int>
with just the elements you want in it to pass a pointer to. Something like:
vector<int> tempVector( foo.begin()+1, foo.end());
// now you can pass &tempVector to your function
However, if your function takes a pointer to an array of int, then you can pass &foo[1]
.
JSON.stringify
returns a String
. So, for example:
var data = [
{ id: 1, name: "bob" },
{ id: 2, name: "john" },
{ id: 3, name: "jake" },
];
JSON.stringify(data)
will return the equivalent of:
"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"
as a String
value.
So when you have
<% for(var i=0; i<JSON.stringify(data).length; i++) {%>
what that ends up looking like is:
<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>
which is probably not what you want. What you probably do want is something like this:
<table>
<% for(var i=0; i < data.length; i++) { %>
<tr>
<td><%= data[i].id %></td>
<td><%= data[i].name %></td>
</tr>
<% } %>
</table>
This will output the following table (using the example data
from above):
<table>
<tr>
<td>1</td>
<td>bob</td>
</tr>
<tr>
<td>2</td>
<td>john</td>
</tr>
<tr>
<td>3</td>
<td>jake</td>
</tr>
</table>
'use strict'
var fs = require("fs");
/***
* implementation of readFileSync
*/
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
/***
* implementation of readFile
*/
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
For better understanding run the above code and compare the results..
SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me
write old function on your fields value for example
<input type="text" name="username" value="{{ old('username') }}">
which means that cacerts keystore isn't password protected
That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:
In order to verify its integrity, you must provide your keystore password.
Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.
You need to call $compile
on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.
In your fiddle, it would look something like this.
$("#dynamicContent").html(
$compile(
"<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
)(scope)
);
Obviously, $compile
must be injected into your controller for this to work.
Read more in the $compile
documentation.
Oh, but that's ugly, non-object-oriented code. The moment you see "if/else" and "typeof", you should be thinking polymorphism. This is the wrong way to go. I think generics are your friend here.
How many types do you plan to deal with?
UPDATE:
If you're just talking about String and int, here's one way you might do it. Start with the interface XmlGenerator (enough with "foo"):
package generics;
public interface XmlGenerator<T>
{
String getXml(T value);
}
And the concrete implementation XmlGeneratorImpl:
package generics;
public class XmlGeneratorImpl<T> implements XmlGenerator<T>
{
private Class<T> valueType;
private static final int DEFAULT_CAPACITY = 1024;
public static void main(String [] args)
{
Integer x = 42;
String y = "foobar";
XmlGenerator<Integer> intXmlGenerator = new XmlGeneratorImpl<Integer>(Integer.class);
XmlGenerator<String> stringXmlGenerator = new XmlGeneratorImpl<String>(String.class);
System.out.println("integer: " + intXmlGenerator.getXml(x));
System.out.println("string : " + stringXmlGenerator.getXml(y));
}
public XmlGeneratorImpl(Class<T> clazz)
{
this.valueType = clazz;
}
public String getXml(T value)
{
StringBuilder builder = new StringBuilder(DEFAULT_CAPACITY);
appendTag(builder);
builder.append(value);
appendTag(builder, false);
return builder.toString();
}
private void appendTag(StringBuilder builder) { this.appendTag(builder, false); }
private void appendTag(StringBuilder builder, boolean isClosing)
{
String valueTypeName = valueType.getName();
builder.append("<").append(valueTypeName);
if (isClosing)
{
builder.append("/");
}
builder.append(">");
}
}
If I run this, I get the following result:
integer: <java.lang.Integer>42<java.lang.Integer>
string : <java.lang.String>foobar<java.lang.String>
I don't know if this is what you had in mind.
For loading a file, I like this a lot better
MemoryStream ms = new MemoryStream();
using (FileStream fs = File.OpenRead(file))
{
fs.CopyTo(ms);
}
importing JSON files are still experimental. It can be supported via the below flag.
--experimental-json-modules
otherwise you can load your JSON file relative to import.meta.url
with fs
directly:-
import { readFile } from 'fs/promises';
const config = JSON.parse(await readFile(new URL('../config.json', import.meta.url)));
you can also use module.createRequire()
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const config = require('../config.json');
If you just want to change the legend title, you can do the following:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.lmplot(
x="total_bill",
y="tip",
hue="smoker",
data=tips,
legend=True
)
g._legend.set_title("New Title")
You may pass an object to the data
option in $.ajax
. jQuery will send this as regular post data, just like a normal HTML form.
$.ajax({
type: "POST",
url: "TelephoneNumbers.aspx/DeleteNumber",
data: dataO, // same as using {numberId: 1, companyId: 531}
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('In Ajax');
}
});
You are calling get with the wrong argument.
It should be:
Object value = field.get(object);
You could try
NumberUtils.isParsable(yourInput)
It is part of org/apache/commons/lang3/math/NumberUtils
and it checks whether the string can be parsed by Integer.parseInt(String)
, Long.parseLong(String)
, Float.parseFloat(String)
or Double.parseDouble(String)
.
See below:
please set dataType config property in your ajax call and give it another try!
another point is you are using ajax call setup configuration properties as string and it is wrong as reference site
$.ajax({
url : 'http://voicebunny.comeze.com/index.php',
type : 'GET',
data : {
'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
alert('Data: '+data);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
I hope be helpful!
Got stuck as I was trying to a go get ... I think it was related to git. Here is how was able to fix it ...
I entered the following in terminal:
sudo xcodebuild -license
This will open the agreement. Go all the way to end and type "agree".
That takes care of go get issues.
It was quite interesting how unrelated things were.
"There should be one -- and preferably only one -- obvious way to do it." So let me add another one. This one is more like "install from sources" for Debian/Ubuntu, from https://github.com/yaml/pyyaml
Install the libYAML and it's headers:
sudo apt-get install libyaml-dev
Download the pyyaml sources:
wget http://pyyaml.org/download/pyyaml/PyYAML-3.13.tar.gz
Install from sources, (don't forget to activate your venv):
. your/env/bin/activate
tar xzf PyYAML-3.13.tar.gz
cd PyYAML-3.13.tar.gz
(env)$ python setup.py install
(env)$ python setup.py test
UPDATE 2
Raw single volume backup bash script:
#!/bin/bash
# This script allows you to backup a single volume from a container
# Data in given volume is saved in the current directory in a tar archive.
CONTAINER_NAME=$1
VOLUME_NAME=$2
usage() {
echo "Usage: $0 [container name] [volume name]"
exit 1
}
if [ -z $CONTAINER_NAME ]
then
echo "Error: missing container name parameter."
usage
fi
if [ -z $VOLUME_NAME ]
then
echo "Error: missing volume name parameter."
usage
fi
sudo docker run --rm --volumes-from $CONTAINER_NAME -v $(pwd):/backup busybox tar cvf /backup/backup.tar $VOLUME_NAME
Raw single volume restore bash script:
#!/bin/bash
# This script allows you to restore a single volume from a container
# Data in restored in volume with same backupped path
NEW_CONTAINER_NAME=$1
usage() {
echo "Usage: $0 [container name]"
exit 1
}
if [ -z $NEW_CONTAINER_NAME ]
then
echo "Error: missing container name parameter."
usage
fi
sudo docker run --rm --volumes-from $NEW_CONTAINER_NAME -v $(pwd):/backup busybox tar xvf /backup/backup.tar
Usage can be like this:
$ volume_backup.sh old_container /srv/www
$ sudo docker stop old_container && sudo docker rm old_container
$ sudo docker run -d --name new_container myrepo/new_container
$ volume_restore.sh new_container
Assumptions are: backup file is named backup.tar, it resides in the same directory as backup and restore script, volume name is the same between containers.
UPDATE
It seems to me that backupping volumes from containers is not different from backupping volumes from data containers.
Volumes are nothing else than paths linked to a container so the process is the same.
I don't know if docker-backup works also for same container volumes but you can use:
sudo docker run --rm --volumes-from yourcontainer -v $(pwd):/backup busybox tar cvf /backup/backup.tar /data
and:
sudo docker run --rm --volumes-from yournewcontainer -v $(pwd):/backup busybox tar xvf /backup/backup.tar
END UPDATE
There is this nice tool available which lets you backup and restore docker volumes containers:
https://github.com/discordianfish/docker-backup
if you have a container linked to some container volumes like this:
$ docker run --volumes-from=my-data-container --name my-server ...
you can backup all the volumes like this:
$ docker-backup store my-server-backup.tar my-server
and restore like this:
$ docker-backup restore my-server-backup.tar
Or you can follow the official way:
\b in regular expressions match word boundaries (i.e. the location between the first word character and non-word character):
$ echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
no bar embarassment
Try This
div.circle {_x000D_
-moz-border-radius: 50px/50px;_x000D_
-webkit-border-radius: 50px 50px;_x000D_
border-radius: 50px/50px;_x000D_
border: solid 21px #f00;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
}_x000D_
_x000D_
div.square {_x000D_
border: solid 21px #f0f;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
}
_x000D_
<div class="circle">_x000D_
<img/>_x000D_
</div>_x000D_
<hr/>_x000D_
<div class="square">_x000D_
<img/>_x000D_
</div>
_x000D_
Try a using namespace std;
at the top of game.h
or use the fully-qualified std::string
instead of string
.
The namespace
in game.cpp
is after the header is included.
Well, the window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.
What about the document object then? The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is also available in short as document.property.
That seems simple enough. But what happens once an IFRAME is introduced?
It can be done via https and oauth or ssh.
https and oauth: create an access token that has "repo" scope and then use this syntax:
"package-name": "git+https://<github_token>:[email protected]/<user>/<repo>.git"
or
ssh: setup ssh and then use this syntax:
"package-name": "git+ssh://[email protected]:<user>/<repo>.git"
(note the use of colon instead of slash before user)
They do different things. exec
replaces the current process with the new process and never returns. system
invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.
I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive
This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.
check out csvreader/writer library at http://www.codeproject.com/KB/cs/CsvReaderAndWriter.aspx
type test struct {
Test string `json:"test"`
}
func test(w http.ResponseWriter, req *http.Request) {
var t test_struct
body, _ := ioutil.ReadAll(req.Body)
json.Unmarshal(body, &t)
fmt.Println(t)
}
Does Python have a string contains substring method?
99% of use cases will be covered using the keyword, in
, which returns True
or False
:
'substring' in any_string
For the use case of getting the index, use str.find
(which returns -1 on failure, and has optional positional arguments):
start = 0
stop = len(any_string)
any_string.find('substring', start, stop)
or str.index
(like find
but raises ValueError on failure):
start = 100
end = 1000
any_string.index('substring', start, end)
Use the in
comparison operator because
>>> 'foo' in '**foo**'
True
The opposite (complement), which the original question asked for, is not in
:
>>> 'foo' not in '**foo**' # returns False
False
This is semantically the same as not 'foo' in '**foo**'
but it's much more readable and explicitly provided for in the language as a readability improvement.
__contains__
The "contains" method implements the behavior for in
. This example,
str.__contains__('**foo**', 'foo')
returns True
. You could also call this function from the instance of the superstring:
'**foo**'.__contains__('foo')
But don't. Methods that start with underscores are considered semantically non-public. The only reason to use this is when implementing or extending the in
and not in
functionality (e.g. if subclassing str
):
class NoisyString(str):
def __contains__(self, other):
print(f'testing if "{other}" in "{self}"')
return super(NoisyString, self).__contains__(other)
ns = NoisyString('a string with a substring inside')
and now:
>>> 'substring' in ns
testing if "substring" in "a string with a substring inside"
True
find
and index
to test for "contains"Don't use the following string methods to test for "contains":
>>> '**foo**'.index('foo')
2
>>> '**foo**'.find('foo')
2
>>> '**oo**'.find('foo')
-1
>>> '**oo**'.index('foo')
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
'**oo**'.index('foo')
ValueError: substring not found
Other languages may have no methods to directly test for substrings, and so you would have to use these types of methods, but with Python, it is much more efficient to use the in
comparison operator.
Also, these are not drop-in replacements for in
. You may have to handle the exception or -1
cases, and if they return 0
(because they found the substring at the beginning) the boolean interpretation is False
instead of True
.
If you really mean not any_string.startswith(substring)
then say it.
We can compare various ways of accomplishing the same goal.
import timeit
def in_(s, other):
return other in s
def contains(s, other):
return s.__contains__(other)
def find(s, other):
return s.find(other) != -1
def index(s, other):
try:
s.index(other)
except ValueError:
return False
else:
return True
perf_dict = {
'in:True': min(timeit.repeat(lambda: in_('superstring', 'str'))),
'in:False': min(timeit.repeat(lambda: in_('superstring', 'not'))),
'__contains__:True': min(timeit.repeat(lambda: contains('superstring', 'str'))),
'__contains__:False': min(timeit.repeat(lambda: contains('superstring', 'not'))),
'find:True': min(timeit.repeat(lambda: find('superstring', 'str'))),
'find:False': min(timeit.repeat(lambda: find('superstring', 'not'))),
'index:True': min(timeit.repeat(lambda: index('superstring', 'str'))),
'index:False': min(timeit.repeat(lambda: index('superstring', 'not'))),
}
And now we see that using in
is much faster than the others.
Less time to do an equivalent operation is better:
>>> perf_dict
{'in:True': 0.16450627865128808,
'in:False': 0.1609668098178645,
'__contains__:True': 0.24355481654697542,
'__contains__:False': 0.24382793854783813,
'find:True': 0.3067379407923454,
'find:False': 0.29860888058124146,
'index:True': 0.29647137792585454,
'index:False': 0.5502287584545229}
Here I create a program to input Name and Age of 5 different persons and perform a selection sort (age wise). I used an class which act as a structure (like C programming language) and a main class to perform the complete operation. Hereunder I'm furnishing the code...
import java.io.*;
class NameList {
String name;
int age;
}
class StructNameAge {
public static void main(String [] args) throws IOException {
NameList nl[]=new NameList[5]; // Create new radix of the structure NameList into 'nl' object
NameList temp=new NameList(); // Create a temporary object of the structure
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
/* Enter data into each radix of 'nl' object */
for(int i=0; i<5; i++) {
nl[i]=new NameList(); // Assign the structure into each radix
System.out.print("Name: ");
nl[i].name=br.readLine();
System.out.print("Age: ");
nl[i].age=Integer.parseInt(br.readLine());
System.out.println();
}
/* Perform the sort (Selection Sort Method) */
for(int i=0; i<4; i++) {
for(int j=i+1; j<5; j++) {
if(nl[i].age>nl[j].age) {
temp=nl[i];
nl[i]=nl[j];
nl[j]=temp;
}
}
}
/* Print each radix stored in 'nl' object */
for(int i=0; i<5; i++)
System.out.println(nl[i].name+" ("+nl[i].age+")");
}
}
The above code is Error Free and Tested... Just copy and paste it into your IDE and ... You know and what??? :)
To get all files (strictly files only) recursively:
Dir.glob('path/**/*').select { |e| File.file? e }
Or anything that's not a directory (File.file?
would reject non-regular files):
Dir.glob('path/**/*').reject { |e| File.directory? e }
Using Find#find
over a pattern-based lookup method like Dir.glob
is actually better. See this answer to "One-liner to Recursively List Directories in Ruby?".
U can use mysql dump or query to export data to csv file
SELECT *
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM products
An analogue of the bat file code in Powershell
Cmd
wmic path Win32_ComputerSystem get Name
Powershell
Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name
and ...
hostname.exe
I ended up doing the following and it works.
public static string Serialize(object obj)
{
using (MemoryStream memoryStream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(memoryStream, obj);
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
public static object Deserialize(string xml, Type toType)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
DataContractSerializer serializer = new DataContractSerializer(toType);
return serializer.ReadObject(reader);
}
}
It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.
I think the annotation you are looking for is:
public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;
And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html
"AND" does not work in my PHP code.
Server's version maybe?
"&&" works fine.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>teste4</groupId>
<artifactId>teste4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bootstrap</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
</dependencies>
</project>
This works for SQL Server Management Studio v18.0
The file "SqlStudio.bin" doesn't seem to exist any longer. Instead my settings are all stored in this file:
C:\Users\*********\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0\UserSettings.xml
<Element>.......</Element>
block
that surrounds it.Add a shortcut:
$.Shortcuts.add({
type: 'down',
mask: 'Ctrl+A',
handler: function() {
debug('Ctrl+A');
}
});
Start reacting to shortcuts:
$.Shortcuts.start();
Add a shortcut to “another” list:
$.Shortcuts.add({
type: 'hold',
mask: 'Shift+Up',
handler: function() {
debug('Shift+Up');
},
list: 'another'
});
Activate “another” list:
$.Shortcuts.start('another');
Remove a shortcut:
$.Shortcuts.remove({
type: 'hold',
mask: 'Shift+Up',
list: 'another'
});
Stop (unbind event handlers):
$.Shortcuts.stop();
Try replacing the AND
with ,
UPDATE shop_category
SET name = 'Secolul XVI - XVIII', name_eng = '16th to 18th centuries'
WHERE category_id = 4768
The UPDATE Syntax shows comma should be used as the separator.
If you're using the variable result:
result = result == "true";
foreach my $key (keys %$ad_grp_ref) {
...
}
Perl::Critic
and daxim recommend the style
foreach my $key (keys %{ $ad_grp_ref }) {
...
}
out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() }
instead of %{ $ad_grp_ref }
)
For ASP.NET 5.0
, I have an extension method as follow:
using System;
using System.ComponentModel;
using System.Security.Claims;
namespace YOUR_PROJECT.Presentation.WebUI.Extensions
{
public static class ClaimsPrincipalExtensions
{
public static TId GetId<TId>(this ClaimsPrincipal principal)
{
if (principal == null || principal.Identity == null ||
!principal.Identity.IsAuthenticated)
{
throw new ArgumentNullException(nameof(principal));
}
var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (typeof(TId) == typeof(string) ||
typeof(TId) == typeof(int) ||
typeof(TId) == typeof(long) ||
typeof(TId) == typeof(Guid))
{
var converter = TypeDescriptor.GetConverter(typeof(TId));
return (TId)converter.ConvertFromInvariantString(loggedInUserId);
}
throw new InvalidOperationException("The user id type is invalid.");
}
public static Guid GetId(this ClaimsPrincipal principal)
{
return principal.GetId<Guid>();
}
}
}
So you can use it like:
using Microsoft.AspNetCore.Mvc;
using YOUR_PROJECT.Presentation.WebUI.Extensions;
namespace YOUR_PROJECT.Presentation.WebUI.Controllers
{
public class YourController :Controller
{
public IActionResult YourMethod()
{
// If it's Guid
var userId = User.GetId();
// Or
// var userId = User.GetId<int>();
return View();
}
}
}
If you don't care about case, then you perhaps it doesn't matter if it returns all upcase:
target.toUpperCase().replace("FOO", "");
In Spring 4.2+ you can now simply do:
@Component
class StartupHousekeeper {
@EventListener(ContextRefreshedEvent.class)
public void contextRefreshedEvent() {
//do whatever
}
}
In my case, the custom UIView class is in an embedded framework. I changed the custom UIView header file to "project" to "public" and include it in the master header file.
Creating a single combined plot with your current data set up would look something like this
p <- ggplot() +
# blue plot
geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) +
geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
colour="darkblue", size=1) +
# red plot
geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) +
geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
colour="red", size=1)
however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner
visual1$group <- 1
visual2$group <- 2
visual12 <- rbind(visual1, visual2)
p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
geom_point() +
geom_smooth(size=1)
As einpoklum mentioned in their answer, since C++17 you can also use structured binding declarations. I want to extend on that by providing a full solution for iterating over a map of maps in a comfortable way:
int main() {
std::map<std::string, std::map<std::string, std::string>> m {
{"name1", {{"value1", "data1"}, {"value2", "data2"}}},
{"name2", {{"value1", "data1"}, {"value2", "data2"}}},
{"name3", {{"value1", "data1"}, {"value2", "data2"}}}
};
for (const auto& [k1, v1] : m)
for (const auto& [k2, v2] : v1)
std::cout << "m[" << k1 << "][" << k2 << "]=" << v2 << std::endl;
return 0;
}
Note 1: For filling the map, I used an initializer list (which is a C++11 feature). This can sometimes be handy to keep fixed initializations compact.
Note 2: If you want to modify the map m
within the loops, you have to remove the const
keywords.
The problem is with your curl options – the RCurl
package doesn't seem to use internet2.dll
.
You need to specify the port separately, and will probably need to give your user login details as network credentials, e.g.,
opts <- list(
proxy = "999.999.999.999",
proxyusername = "mydomain\\myusername",
proxypassword = "mypassword",
proxyport = 8080
)
getURL("http://stackoverflow.com", .opts = opts)
Remember to escape any backslashes in your password. You may also need to wrap the URL in a call to curlEscape
.
Like for me -> working is:
string strUri2 = Directory.GetCurrentDirectory()+@"/Images/ok_progress.png";
image1.Source = new BitmapImage(new Uri(strUri2));
Append the below Script in Console:
window.addEventListener("beforeunload", function(event) {
console.log("The page is redirecting")
debugger;
});
Using svcutil, you can create interfaces and classes (data contracts) from the WSDL.
svcutil your.wsdl (or svcutil your.wsdl /l:vb if you want Visual Basic)
This will create a file called "your.cs" in C# (or "your.vb" in VB.NET) which contains all the necessary items.
Now, you need to create a class "MyService" which will implement the service interface (IServiceInterface) - or the several service interfaces - and this is your server instance.
Now a class by itself doesn't really help yet - you'll need to host the service somewhere. You need to either create your own ServiceHost instance which hosts the service, configure endpoints and so forth - or you can host your service inside IIS.
Code will be As below.
[textarea id:message 0x0 class:custom-class "Insert text here"]<!-- No Rows No columns -->
[textarea id:message x2 class:custom-class "Insert text here"]<!-- Only Rows -->
[textarea id:message 12x class:custom-class "Insert text here"]<!-- Only Columns -->
[textarea id:message 10x2 class:custom-class "Insert text here"]<!-- Both Rows and Columns -->
For Details: https://contactform7.com/text-fields/
Similar as they are, merge!
and store
treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!
's key: "value"
syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.
hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash
{:key=>"value"}
hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash
{:key=>"value", "key"=>"value"}
To get the shovel operator <<
working, I would advise using Mark Thomas's answer.
<html:form name="Form" type="abc" action="abc.do" method="get" onsubmit="return false;">
method="get"
- resolves the problem.
if method="post"
then only warning comes.
I got a similar error, and it's caused by incorrect proxy setting. This command saved me:
git config --global --unset http.proxy
https version:
git config --global --unset https.proxy
According to theory its the same things. Recursion and loop with the same O() complexity will work with the same theoretical speed, but of course real speed depends on language, compiler and processor. Example with power of number can be coded in iteration way with O(ln(n)):
int power(int t, int k) {
int res = 1;
while (k) {
if (k & 1) res *= t;
t *= t;
k >>= 1;
}
return res;
}
I found AlecRust's solution quite helpful, but I add something to resolve one problem: When you click on a single accordion to expand it and then you click on the button to expand, they will all be opened. But, if you click again on the button to collapse, the single accordion expand before won't be collapse.
I've used imageButton, but you can also apply that logic to buttons.
/*** Expand all ***/
$(".expandAll").click(function (event) {
$('.accordion .ui-accordion-header:not(.ui-state-active)').next().slideDown();
return false;
});
/*** Collapse all ***/
$(".collapseAll").click(function (event) {
$('.accordion').accordion({
collapsible: true,
active: false
});
$('.accordion .ui-accordion-header').next().slideUp();
return false;
});
Also, if you have accordions inside an accordion and you want to expand all only on that second level, you can add a query:
/*** Expand all Second Level ***/
$(".expandAll").click(function (event) {
$('.accordion .ui-accordion-header:not(.ui-state-active)').nextAll(':has(.accordion .ui-accordion-header)').slideDown();
return false;
});
Here i get the answer for that question . After searching for too long finally i get to crack the key and password for this . I forget my key and alias also the jks file but fortunately i know the bunch of password what i had put in it . but finding correct combinations for that was toughest task for me .
Solution - Download this - Keytool IUI version 2.4.1 plugin
the window will pop up now it show the alias name ..if you jks file is correct .. right click on alias and hit "view certificates chain ".. it will show the SHA1 Key .. match this key with tha key you get while you was uploading the apk in google app store ...
if it match then you are with the right jks file and alias ..
now lucky i have bunch of password to match ..
now go to this scrren put the same jks path .. and password(among the password you have ) put any path in "Certificate file"
if the screen shows any error then password is not matching .. if it doesn't show any error then it means you are with correct jks file . correct alias and password() now with that you can upload your apk in play store :)
One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.
export function foo() { console.log('foo') },
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }
In this case you are export all of the functions with names, so you could do
import * as fns from './foo';
to get an object with properties for each function instead of the import you'd use for your first example:
import fns from './foo';
+------+----------------------+
| type | names |
+------+----------------------+
| cat | Felon |
| cat | Purz |
| dog | Fido |
| dog | Beethoven |
| dog | Buddy |
| bird | Tweety |
+------+----------------------+
select group_concat(name) from Pets
group by type
Here you can easily get the answer in single SQL and by using group by in your SQL you can separate the result based on that column value. Also you can use your own custom separator for splitting values
Result:
+------+----------------------+
| type | names |
+------+----------------------+
| cat | Felon,Purz |
| dog | Fido,Beethoven,Buddy |
| bird | Tweety |
+------+----------------------+
As Niraj suggested, use a SortableBindingList. I've used this very successfully with the DataGridView.
Here's a link to the updated code I used - Presenting the SortableBindingList - Take Two - archive
Just add the two source files to your project, and you'll be in business.
Source is in SortableBindingList.zip - 404 dead link
If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.
if (isset($_POST['mycheckbox'])) {
echo "checked!";
}
There is no standard C++ way to do this without resorting to C-style varargs (...
).
There are of course default arguments that sort of "look" like variable number of arguments depending on the context:
void myfunc( int i = 0, int j = 1, int k = 2 );
// other code...
myfunc();
myfunc( 2 );
myfunc( 2, 1 );
myfunc( 2, 1, 0 );
All four function calls call myfunc
with varying number of arguments. If none are given, the default arguments are used. Note however, that you can only omit trailing arguments. There is no way, for example to omit i
and give only j
.
\n
This means insert a newline in the text at this point.
Just example
System.out.println("hello\nworld");
Output:
hello
world
call chooseImage method like-
public void chooseImage(ImageView v)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(imageReturnedIntent != null)
{
Uri selectedImage = imageReturnedIntent.getData();
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK)
{
Bitmap datifoto = null;
temp.setImageBitmap(null);
Uri picUri = null;
picUri = imageReturnedIntent.getData();//<- get Uri here from data intent
if(picUri !=null){
try {
datifoto = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri);
temp.setImageBitmap(datifoto);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (OutOfMemoryError e) {
Toast.makeText(getBaseContext(), "Image is too large. choose other", Toast.LENGTH_LONG).show();
}
}
}
break;
}
}
else
{
//Toast.makeText(getBaseContext(), "data null", Toast.LENGTH_SHORT).show();
}
}
Also make sure you test it both in firefox and IE. There are some nasty bugs with JS manipulated checkboxes.
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
Going to keep this pithier, this is already asked and answered above .
I'd step back however and answer it slightly differently, the docker engine itself adds orchestration as one of its extras and this is the disruptive part. Once you start running an app as a combination of containers running 'somewhere' across multiple container engines it gets really exciting. Robustness, Horizontal Scaling, complete abstraction from the underlying hardware, i could go on and on...
Its not just Docker that gives you this, in fact the de facto Container Orchestration standard is Kubernetes which comes in a lot of flavours, a Docker one, but also OpenShift, SuSe, Azure, AWS...
Then beneath K8S there are alternative container engines; the interesting ones are Docker and CRIO - recently built, daemonless, intended as a container engine specifically for Kubernetes but immature. Its the competition between these that I think will be the real long term choice for a container engine.
I wasn't completely happy by the --allow-file-access-from-files
solution, because I'm using Chrome as my primary browser, and wasn't really happy with this breach I was opening.
Now I'm using Canary ( the chrome beta version ) for my development with the flag on. And the mere Chrome version for my real blogging : the two browser don't share the flag !
So are you trying to grep through older versions of the code looking to see where something last exists?
If I were doing this, I would probably use git bisect. Using bisect, you can specify a known good version, a known bad version, and a simple script that does a check to see if the version is good or bad (in this case a grep to see if the code you are looking for is present). Running this will find when the code was removed.
CSS lets you use custom fonts, downloadable fonts on your website. You can download the font of your preference, let’s say myfont.ttf
, and upload it to your remote server where your blog or website is hosted.
@font-face {
font-family: myfont;
src: url('myfont.ttf');
}
Make your life easy when working with dates, timestamps and durations. Use HalDateTime from
http://sourceforge.net/projects/haldatetime/?source=directory
For example you can just use it to parse your input like this:
HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate ); // will print in ISO format: 1988-12-25
You can also specify patterns for parsing and printing.
image_view.getLayoutParams().height
returns height value in pixels. You need to get the screen dimensions first to set the values properly.
Display display = context.getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
int screen_height = outMetrics.heightPixels;
int screen_width = outMetrics.widthPixels;
After you get the screen dimensions, you can set the imageview width&height using proper margins.
view.getLayoutParams().height = screen_height - 140;
view.getLayoutParams().width = screen_width - 130 ;
For Windows users
I usually upgrade Yarn with Chocolatey.
choco upgrade yarn
I'f you're suppsed to be able to use it, then 3rd-party library should have a *.lib file as well as a *.dll file. You simply need to add the *.lib to the list of input file in your project's 'Linker' options.
This *.lib file isn't necessarily a 'static' library (which contains code): instead a *.lib can be just a file that links your executable to the DLL.
If this problem persists, you may want to check all path values in the PATH variable (under Control Panel\System and Security\System\Advanced System Settings
). It might be that some other path is invalid or contains an illegal character.
Today, I had the same problem and found a double quote in a different path value in the PATH variable. All paths after that (including a fresly installed conda) were not usable. Removing the double quote solved the problem.